Object – Oriented Programming
Week 5 –Arrays
Ferdin Joe John Joseph, PhD
Faculty of Information Technology
Thai-Nichi Institute of Technology
Arrays
Faculty of Information Technology,
Thai-Nichi Institute of Technology
2
3
Introducing Arrays
Array is a data structure that represents a collection
of the same types of data.
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
double[] myList = new double[10];
myList reference
myList[0]
myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value
Array reference
variable
Array element at
index 5
4
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
• datatype arrayRefVar[]; // This style is
allowed, but not preferred
Example:
double myList[];
5
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the first element in the
array.
myList[9] references the last element in the
array.
6
Declaring and Creating
in One Step
• datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];
• datatype arrayRefVar[] = new
datatype[arraySize];
double myList[] = new double[10];
7
The Length of an Array
Once an array is created, its size is fixed. It
cannot be changed. You can find its size using
arrayRefVar.length
For example,
myList.length returns 10
8
Default Values
When an array is created, its elements are
assigned the default value of
0 for the numeric primitive data types,
'u0000' for char types, and
false for boolean types.
9
Indexed Variables
The array elements are accessed through the
index. The array indices are 0-based, i.e., it starts
from 0 to arrayRefVar.length-1. In the example in
Figure 6.1, myList holds ten double values and the
indices are from 0 to 9.
Each element in the array is represented using the
following syntax, known as an indexed variable:
arrayRefVar[index];
10
Using Indexed Variables
After an array is created, an indexed
variable can be used in the same way as a
regular variable. For example, the following
code adds the value in myList[0] and
myList[1] to myList[2].
myList[2] = myList[0] + myList[1];
11
Array Initializers
• Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one
statement.
12
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the
following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
13
CAUTION
Using the shorthand notation, you
have to declare, create, and
initialize the array all in one
statement. Splitting it would cause
a syntax error. For example, the
following is wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
14
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
Declare array variable values, create
an array, and assign its reference to
values
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
15
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i becomes 1
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
16
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=1) is less than 5
After the array is created
0
1
2
3
4
0
0
0
0
0
animation
17
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line is executed, value[1] is 1
After the first iteration
0
1
2
3
4
0
1
0
0
0
animation
18
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After i++, i becomes 2
animation
After the first iteration
0
1
2
3
4
0
1
0
0
0
19
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = values[i] + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (= 2) is less than 5
animation
After the first iteration
0
1
2
3
4
0
1
0
0
0
20
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line is executed,
values[2] is 3 (2 + 1)
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
21
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, i becomes 3.
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
22
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=3) is still less than 5.
After the second iteration
0
1
2
3
4
0
1
3
0
0
animation
23
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line, values[3] becomes 6 (3 + 3)
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
24
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, i becomes 4
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
25
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i (=4) is still less than 5
After the third iteration
0
1
2
3
4
0
1
3
6
0
animation
26
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this, values[4] becomes 10 (4 + 6)
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
animation
27
Trace Program with Arrays
public class Test {
public static void main(String[]
args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After i++, i becomes 5
animation
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
28
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
i ( =5) < 5 is false. Exit the loop
animation
After the fourth iteration
0
1
2
3
4
0
1
3
6
10
29
Trace Program with Arrays
public class Test {
public static void main(String[] args)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
After this line, values[0] is 11 (1 + 10)
0
1
2
3
4
11
1
3
6
10
animation
30
Processing Arrays
See the examples in the text.
1. (Initializing arrays)
2. (Printing arrays)
3. (Summing all elements)
4. (Finding the largest element)
5. (Finding the smallest index of the
largest element)
31
Enhanced for Loop
JDK 1.5 introduced a new for loop that enables you to traverse the
complete array sequentially without using an index variable. For example,
the following code displays all elements in the array myList:
for (double value: myList)
System.out.println(value);
In general, the syntax is
for (elementType value: arrayRefVar) {
// Process the value
}
You still have to use an index variable if you wish to traverse the array in a
different order or change the elements in the array.
JDK 1.5
Feature
32
Example: Assigning Grades
• Objective: read student scores (int), get the
best score, and then assign grades based on
the following scheme:
– Grade is A if score is >= best–10;
– Grade is B if score is >= best–20;
– Grade is C if score is >= best–30;
– Grade is D if score is >= best–40;
– Grade is F otherwise.
33
Copying Arrays
Often, in a program, you need to duplicate an array or a part of
an array. In such cases you could attempt to use the assignment
statement (=), as follows:
list2 = list1;
Contents
of list1
list1
Contents
of list2
list2
Before the assignment
list2 = list1;
Contents
of list1
list1
Contents
of list2
list2
After the assignment
list2 = list1;
Garbage
34
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];
for (int i = 0; i < sourceArrays.length; i++)
targetArray[i] = sourceArray[i];
35
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);
Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
36
Linear Search
The linear search approach compares the
key element, key, sequentially with each
element in the array list. The method
continues to do so until the key matches
an element in the list or the list is
exhausted without a match being found. If
a match is made, the linear search returns
the index of the element in the array that
matches the key. If no match is found, the
search returns -1.
37
Linear Search Animation
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
6 4 1 9 7 3 2 8
3
3
3
3
3
3
animation
Key List
38
From Idea to Solution
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < list.length; i++)
if (key == list[i])
return i;
return -1;
}
int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // returns 1
int j = linearSearch(list, -4); // returns -1
int k = linearSearch(list, -3); // returns 5
Trace the method
Two-Dimensional Arrays
• A one-dimensional array stores a list of
elements
• A two-dimensional array can be thought
of as a table of elements, with rows and
columns
one
dimension
two
dimensions
Two-Dimensional Arrays
• To be precise, in Java a two-dimensional array is an
array of arrays
• A two-dimensional array is declared by specifying the
size of each dimension separately:
int[][] scores = new int[12][50];
• A array element is referenced using two index values:
value = scores[3][6]
• The array stored in one row can be specified using
one index
Arrays of Arrays
• Two-Dimensional arrays
– float[][] temperature=new float[10][365];
– 10 arrays each having 365 elements
– First index: specifies array (row)
– Second Index: specifies element in that array
(column)
– In JAVA float is 4 bytes, total
Size=4*10*365=14,600 bytes
Graphical Representation
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
Sample[0]
Sample[1]
Sample[2]
Initializing Array of Arrays
int[][] array2D = { {99, 42, 74, 83, 100}, {90,
91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61,
89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50,
65, 92, 87, 94}, {43, 98, 78, 56, 99} };
//5 rows with 5 elements each
Arrays of Arrays of Varying
Length
• All arrays do not have to be of the same
length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=new float[101];
• Not required to define all arrays
Initializing Varying Size Arrays
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
Array of Arrays Length
long[][] primes = new long[20][];
primes[2] = new long[30];
System.out.println(primes.length); //Number of arrays
System.out.println(primes[2].length);//Number of elements in the second array
OUTPUT:
20
30
Sample Program
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
// print out the array
for ( int row=0; row < uneven.length; row++ ) //changes row
{
System.out.print("Row " + row + ": ");
for ( int col=0; col < uneven[row].length; col++ ) //changes column
System.out.print( uneven[row][col] + " ");
System.out.println();
}
}
}
Output
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4
Faculty of Information Technology,
Thai-Nichi Institute of Technology
49
An Ordered Collection: ArrayList
• ArrayList is a Java class that specializes in
representing an ordered collection of things
• The ArrayList class is defined in the Java
libraries
– part of the java.util package
• We can store any kind of object in an ArrayList
– myList.add(theDog);
• We can retrieve an object from the ArrayList by
specifying its index number
– myList.get(0)
Faculty of Information Technology,
Thai-Nichi Institute of Technology
50
ArrayList
• ArrayList()
– This constructor builds an empty list with an initial
capacity of 10
• int size()
– This method returns the number of elements in this
list
• boolean add(Object o)
– This method appends the specified element to the
end of this list and increases the size of the array if
needed
• Object get(int index)
– This method returns the element at the specified
position
Faculty of Information Technology,
Thai-Nichi Institute of Technology
51
Using ArrayLists
• ArrayList is part of the java.util package
– import java.util.*; to use ArrayList
• Creating a list
• ArrayList names = new ArrayList ( );
• Getting the size
• int numberOfNames = names.size( );
• Adding things
• names.add("Billy");
• names.add("Susan");
• names.add("Frodo");
NameList.java
Faculty of Information Technology,
Thai-Nichi Institute of Technology
52
Using ArrayLists : import
• ArrayList is part of the java.util package
– import java.util.ArrayList; to use ArrayList
• The import statement tells the Java
compiler where to look when it can’t find a
class definition in the local directory
– We tell the compiler to look in package
java.util for the definition of ArrayList by
putting an import statement at the top of the
source code file
– Java always looks in package java.lang on its
own
Faculty of Information Technology,
Thai-Nichi Institute of Technology
53
Using ArrayLists : constructor
• Creating a new ArrayList object
• ArrayList names = new ArrayList ( );
• There are several constructors available
– ArrayList()
• Construct an empty list with an initial capacity of 10
– ArrayList(int initialCapacity)
• Construct an empty list with the specified initial capacity
– ArrayList(Collection c)
• Construct a list containing elements from another collection
Faculty of Information Technology,
Thai-Nichi Institute of Technology
54
Using ArrayLists : size
• Getting the size
• int numberOfNames = names.size( );
• size() method returns integer value that
caller can use to control looping, check for
limits, etc
– Design pattern: The object keeps track of
relevant information, and can tell the caller when
there is a need to know
Faculty of Information Technology,
Thai-Nichi Institute of Technology
55
Using ArrayLists : add
• Adding things
• names.add("Billy");
• add(Object o) method adds an object to the
list at the end of the list
• The object can be of any class type
– String, File, InputStream, …
– can’t add “primitive” types like int or double
directly
• Can use the wrapper classes like Integer to store
primitives
Faculty of Information Technology,
Thai-Nichi Institute of Technology
56
Using ArrayLists: get
• ArrayLists provide indexed access
– We can ask for the ith item of the list, where
the first item is at index 0, the second at index
1, and the last item is at index n-1 (where n is
the size of the collection).
ArrayList names = new ArrayList ( );
names.add("Billy");
names.add("Susan");
Object x = names.get(0);
Object y = names.get(1);

DSA 103 Object Oriented Programming :: Week 5

  • 1.
    Object – OrientedProgramming Week 5 –Arrays Ferdin Joe John Joseph, PhD Faculty of Information Technology Thai-Nichi Institute of Technology
  • 2.
    Arrays Faculty of InformationTechnology, Thai-Nichi Institute of Technology 2
  • 3.
    3 Introducing Arrays Array isa data structure that represents a collection of the same types of data. 5.6 4.5 3.3 13.2 4 34.33 34 45.45 99.993 11123 double[] myList = new double[10]; myList reference myList[0] myList[1] myList[2] myList[3] myList[4] myList[5] myList[6] myList[7] myList[8] myList[9] Element value Array reference variable Array element at index 5
  • 4.
    4 Declaring Array Variables •datatype[] arrayRefVar; Example: double[] myList; • datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];
  • 5.
    5 Creating Arrays arrayRefVar =new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.
  • 6.
    6 Declaring and Creating inOne Step • datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10]; • datatype arrayRefVar[] = new datatype[arraySize]; double myList[] = new double[10];
  • 7.
    7 The Length ofan Array Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayRefVar.length For example, myList.length returns 10
  • 8.
    8 Default Values When anarray is created, its elements are assigned the default value of 0 for the numeric primitive data types, 'u0000' for char types, and false for boolean types.
  • 9.
    9 Indexed Variables The arrayelements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. In the example in Figure 6.1, myList holds ten double values and the indices are from 0 to 9. Each element in the array is represented using the following syntax, known as an indexed variable: arrayRefVar[index];
  • 10.
    10 Using Indexed Variables Afteran array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the value in myList[0] and myList[1] to myList[2]. myList[2] = myList[0] + myList[1];
  • 11.
    11 Array Initializers • Declaring,creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
  • 12.
    12 Declaring, creating, initializing Usingthe Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
  • 13.
    13 CAUTION Using the shorthandnotation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};
  • 14.
    14 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } Declare array variable values, create an array, and assign its reference to values After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 15.
    15 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } i becomes 1 After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 16.
    16 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } i (=1) is less than 5 After the array is created 0 1 2 3 4 0 0 0 0 0 animation
  • 17.
    17 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line is executed, value[1] is 1 After the first iteration 0 1 2 3 4 0 1 0 0 0 animation
  • 18.
    18 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 2 animation After the first iteration 0 1 2 3 4 0 1 0 0 0
  • 19.
    19 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4]; } } i (= 2) is less than 5 animation After the first iteration 0 1 2 3 4 0 1 0 0 0
  • 20.
    20 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line is executed, values[2] is 3 (2 + 1) After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 21.
    21 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, i becomes 3. After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 22.
    22 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=3) is still less than 5. After the second iteration 0 1 2 3 4 0 1 3 0 0 animation
  • 23.
    23 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line, values[3] becomes 6 (3 + 3) After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 24.
    24 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, i becomes 4 After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 25.
    25 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=4) is still less than 5 After the third iteration 0 1 2 3 4 0 1 3 6 0 animation
  • 26.
    26 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, values[4] becomes 10 (4 + 6) After the fourth iteration 0 1 2 3 4 0 1 3 6 10 animation
  • 27.
    27 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 5 animation After the fourth iteration 0 1 2 3 4 0 1 3 6 10
  • 28.
    28 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i ( =5) < 5 is false. Exit the loop animation After the fourth iteration 0 1 2 3 4 0 1 3 6 10
  • 29.
    29 Trace Program withArrays public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line, values[0] is 11 (1 + 10) 0 1 2 3 4 11 1 3 6 10 animation
  • 30.
    30 Processing Arrays See theexamples in the text. 1. (Initializing arrays) 2. (Printing arrays) 3. (Summing all elements) 4. (Finding the largest element) 5. (Finding the smallest index of the largest element)
  • 31.
    31 Enhanced for Loop JDK1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array. JDK 1.5 Feature
  • 32.
    32 Example: Assigning Grades •Objective: read student scores (int), get the best score, and then assign grades based on the following scheme: – Grade is A if score is >= best–10; – Grade is B if score is >= best–20; – Grade is C if score is >= best–30; – Grade is D if score is >= best–40; – Grade is F otherwise.
  • 33.
    33 Copying Arrays Often, ina program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1; Contents of list1 list1 Contents of list2 list2 Before the assignment list2 = list1; Contents of list1 list1 Contents of list2 list2 After the assignment list2 = list1; Garbage
  • 34.
    34 Copying Arrays Using aloop: int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];
  • 35.
    35 The arraycopy Utility arraycopy(sourceArray,src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
  • 36.
    36 Linear Search The linearsearch approach compares the key element, key, sequentially with each element in the array list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1.
  • 37.
    37 Linear Search Animation 64 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 3 3 3 3 3 3 animation Key List
  • 38.
    38 From Idea toSolution /** The method for finding a key in the list */ public static int linearSearch(int[] list, int key) { for (int i = 0; i < list.length; i++) if (key == list[i]) return i; return -1; } int[] list = {1, 4, 4, 2, 5, -3, 6, 2}; int i = linearSearch(list, 4); // returns 1 int j = linearSearch(list, -4); // returns -1 int k = linearSearch(list, -3); // returns 5 Trace the method
  • 39.
    Two-Dimensional Arrays • Aone-dimensional array stores a list of elements • A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions
  • 40.
    Two-Dimensional Arrays • Tobe precise, in Java a two-dimensional array is an array of arrays • A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; • A array element is referenced using two index values: value = scores[3][6] • The array stored in one row can be specified using one index
  • 41.
    Arrays of Arrays •Two-Dimensional arrays – float[][] temperature=new float[10][365]; – 10 arrays each having 365 elements – First index: specifies array (row) – Second Index: specifies element in that array (column) – In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
  • 42.
    Graphical Representation 0 12 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 Sample[0] Sample[1] Sample[2]
  • 43.
    Initializing Array ofArrays int[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99} }; //5 rows with 5 elements each
  • 44.
    Arrays of Arraysof Varying Length • All arrays do not have to be of the same length float[][] samples; samples=new float[6][];//defines # of arrays samples[2]=new float[6]; samples[5]=new float[101]; • Not required to define all arrays
  • 45.
    Initializing Varying SizeArrays int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; //Three arrays //First array has 3 elements //Second array has 2 elements //Third array has 5 elements
  • 46.
    Array of ArraysLength long[][] primes = new long[20][]; primes[2] = new long[30]; System.out.println(primes.length); //Number of arrays System.out.println(primes[2].length);//Number of elements in the second array OUTPUT: 20 30
  • 47.
    Sample Program class unevenExample3 { publicstatic void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; // print out the array for ( int row=0; row < uneven.length; row++ ) //changes row { System.out.print("Row " + row + ": "); for ( int col=0; col < uneven[row].length; col++ ) //changes column System.out.print( uneven[row][col] + " "); System.out.println(); } } }
  • 48.
    Output Row 0: 19 4 Row 1: 0 2 Row 2: 0 1 2 3 4
  • 49.
    Faculty of InformationTechnology, Thai-Nichi Institute of Technology 49 An Ordered Collection: ArrayList • ArrayList is a Java class that specializes in representing an ordered collection of things • The ArrayList class is defined in the Java libraries – part of the java.util package • We can store any kind of object in an ArrayList – myList.add(theDog); • We can retrieve an object from the ArrayList by specifying its index number – myList.get(0)
  • 50.
    Faculty of InformationTechnology, Thai-Nichi Institute of Technology 50 ArrayList • ArrayList() – This constructor builds an empty list with an initial capacity of 10 • int size() – This method returns the number of elements in this list • boolean add(Object o) – This method appends the specified element to the end of this list and increases the size of the array if needed • Object get(int index) – This method returns the element at the specified position
  • 51.
    Faculty of InformationTechnology, Thai-Nichi Institute of Technology 51 Using ArrayLists • ArrayList is part of the java.util package – import java.util.*; to use ArrayList • Creating a list • ArrayList names = new ArrayList ( ); • Getting the size • int numberOfNames = names.size( ); • Adding things • names.add("Billy"); • names.add("Susan"); • names.add("Frodo"); NameList.java
  • 52.
    Faculty of InformationTechnology, Thai-Nichi Institute of Technology 52 Using ArrayLists : import • ArrayList is part of the java.util package – import java.util.ArrayList; to use ArrayList • The import statement tells the Java compiler where to look when it can’t find a class definition in the local directory – We tell the compiler to look in package java.util for the definition of ArrayList by putting an import statement at the top of the source code file – Java always looks in package java.lang on its own
  • 53.
    Faculty of InformationTechnology, Thai-Nichi Institute of Technology 53 Using ArrayLists : constructor • Creating a new ArrayList object • ArrayList names = new ArrayList ( ); • There are several constructors available – ArrayList() • Construct an empty list with an initial capacity of 10 – ArrayList(int initialCapacity) • Construct an empty list with the specified initial capacity – ArrayList(Collection c) • Construct a list containing elements from another collection
  • 54.
    Faculty of InformationTechnology, Thai-Nichi Institute of Technology 54 Using ArrayLists : size • Getting the size • int numberOfNames = names.size( ); • size() method returns integer value that caller can use to control looping, check for limits, etc – Design pattern: The object keeps track of relevant information, and can tell the caller when there is a need to know
  • 55.
    Faculty of InformationTechnology, Thai-Nichi Institute of Technology 55 Using ArrayLists : add • Adding things • names.add("Billy"); • add(Object o) method adds an object to the list at the end of the list • The object can be of any class type – String, File, InputStream, … – can’t add “primitive” types like int or double directly • Can use the wrapper classes like Integer to store primitives
  • 56.
    Faculty of InformationTechnology, Thai-Nichi Institute of Technology 56 Using ArrayLists: get • ArrayLists provide indexed access – We can ask for the ith item of the list, where the first item is at index 0, the second at index 1, and the last item is at index n-1 (where n is the size of the collection). ArrayList names = new ArrayList ( ); names.add("Billy"); names.add("Susan"); Object x = names.get(0); Object y = names.get(1);