6. Array Processing – Sample1 double [] rainfall = new double [ 12 ] ; double annualAverage, sum = 0.0; for ( int i = 0; i < rainfall.length; i++ ) { rainfall [ i ] = Double.parseDouble ( JOptionPane.showinputDialog ( null , "Rainfall for month " + ( i+1 ) ) ) ; sum += rainfall [ i ] ; } annualAverage = sum / rainfall.length; The public constant length returns the capacity of an array.
7. Array Processing – Sample 2 double [] rainfall = new double [ 12 ] ; String [] monthName = new String [ 12 ] ; monthName [ 0 ] = "January" ; monthName [ 1 ] = "February" ; … double annualAverage, sum = 0.0; for ( int i = 0; i < rainfall.length; i++ ) { rainfall [ i ] = Double.parseDouble ( JOptionPane.showinputDialog ( null , "Rainfall for " + monthName [ i ] )) ; sum += rainfall [ i ] ; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. The actual month name instead of a number.
8.
9.
10.
11.
12.
13. Creating an Object Array - 1 Code State of Memory Only the name person is declared, no array is allocated yet. Person [ ] person; person = new Person [ 20 ] ; person [ 0 ] = new Person ( ) ; A After is executed A person
14. Creating an Object Array - 2 Code State of Memory Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. person Person [ ] person; person = new Person [ 20 ] ; person [ 0 ] = new Person ( ) ; B After is executed B 0 1 2 3 4 16 17 18 19 person
15. Creating an Object Array - 3 Code State of Memory One Person object is created and the reference to this object is placed in position 0. Person [ ] person; person = new Person [ 20 ] ; person [ 0 ] = new Person ( ) ; C 0 1 2 3 4 16 17 18 19 person 0 1 2 3 4 16 17 18 19 person After is executed C Person
16.
17.
18. Object Deletion – Approach 1 Delete Person B by setting the reference in position 1 to null. int delIdx = 1; person [ delIdx ] = null ; 0 1 2 3 person A B C D A 0 1 2 3 person A C D Before is executed A After is executed A
19. Object Deletion – Approach 2 Delete Person B by setting the reference in position 1 to the last person. int delIdx = 1, last = 3; person [ delIndex ] = person [ last ] ; person [ last ] = null ; 0 1 2 3 person A B C D A 0 1 2 3 person A C D Before is executed A After is executed A
20.
21. Passing Arrays to Methods - 1 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } A. Local variable number does not exist before the method execution A At before searchMinimum A arrayOne
22. Passing Arrays to Methods - 2 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } B. The value of the argument, which is an address, is copied to the parameter. arrayOne B arrayOne The address is copied at B number
23. Passing Arrays to Methods - 3 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } C. The array is accessed via number inside the method. arrayOne number While at inside the method C C
24. Passing Arrays to Methods - 4 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } D. The parameter is erased. The argument still points to the same object. arrayOne number D arrayOne At after searchMinimum D
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
Notes de l'éditeur
We will cover the basic array processing in this lesson, manipulating arrays of primitive data types and objects.
Suppose you need to handle up to 300 Student objects in a program for maintaining a high school alumni list, would you use 300 variables? Suppose you need to process daily temperatures for a 12-month period in a science project, would you use 365 variables? You can, but would you? To manipulate a collection of data, we can use arrays.
As you can declare and create objects in one statement such as Person p = new Person( ); you can declare and create an array in one statement as double[ ] rainfall = new double[12]; Strictly speaking, an array is a reference data type and really an object because there is no class called Array in Java. The thumbnail note in page 413 is therefore not 100 percent accurate.
This code computes the average annual rainfall. Notice the public constant length returns the capacity, not the actual number of non-blank values in the array.
This code also computes the average annual rainfall, but this time we use the second array, an arrray of String so the prompt becomes &quot;Rainfall for January&quot;, &quot;Rainfall for February&quot;, and so forth. Notice how the monthName array is used in the for loop.
This code computes the average rainfall for each quarter. The inner loop is used to compute the rainfall for a given quarter. The outer loop processes the four quarters. This is how the values for i, j, and 3*i+j change: i j 3*i+j 0 0 0 1 1 2 2 1 0 3 1 4 2 5 2 0 6 1 7 2 8 3 0 9 1 10 2 11 The sample code is equivalent to for (int i = 0; i < 3; i++ ) { quarterAverage[0] += rainfall[i]; quarterAverage[1] += rainfall[i+3]; quarterAverage[2] += rainfall[i+6]; quarterAverage[3] += rainfall[i+9]; } quarterAverage[0] = quarterAverage[0] / 3.0; quarterAverage[1] = quarterAverage[1] / 3.0; quarterAverage[2] = quarterAverage[2] / 3.0; quarterAverage[3] = quarterAverage[3] / 3.0;
When an array is initialized in this manner, its capacity is set to the number of elements in the list.
Instead of declaring the array size to a fixed value, it is possible to declare its size at the runtime. For example, we can prompt the user for the size of an array as illustrated in the sample code shown here.
By combining the power of arrays and objects, we can structure programs in a clean, logical manner. Without an array of objects, to represent a collection of Account objects, for example, we need to use several different arrays, one for names, one for addresses, and so forth. This is very cumbersome and error-prone.
The indexed expression person[i] is used to refer to the (i+1)st object in the person array. Since this expression refers to an object, we write person[i].setAge( 20 ); to call this Person object’s setAge method, for example. This is the syntax we use to call an object’s method. We are just using an indexed expression to refer to an object instead of a simple variable.
Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() > oldest.getAge() ) { oldest = person[i]; //found an older person } } outputBox.printLine(&quot;Oldest : &quot; + oldest.getName() + &quot; is &quot; + oldest.getAge() + &quot; years old.&quot;); outputBox.printLine(&quot;Youngest: &quot; + youngest.getName() + &quot; is &quot; + youngest.getAge() + &quot; years old.&quot;);
In this approach, we simply leave the position of a deleted object to a null. With this approach, an array index positions will be a mixture of null and real pointers.
With the second approach, we divide the array into two parts: the first part contains the real references and the second part contains the null references. When we delete a node, a hole will result and we must fill this hole. There are two possible solutions. The first solution is to pack the elements. If an object at position J is removed (i.e., this position is set to null), then elements from position J+1 till the last non-null reference are shifted one position lower. And, finally, the last non-null reference is set to null. The second solution is to replace the removed element by the last element in the array. The first solution is necessary if the Person objects are arranged in some order (e.g., in ascending order of age). The second solution is a better one if the Person objects are not arranged in any order.
Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() > oldest.getAge() ) { oldest = person[i]; //found an older person } } System.out.println(&quot;Oldest : &quot; + oldest.getName() + &quot; is &quot; + oldest.getAge() + &quot; years old.&quot;); System.out.println(&quot;Youngest: &quot; + youngest.getName() + &quot; is &quot; + youngest.getAge() + &quot; years old.&quot;);
When an array is passed to a method, only its reference is passed. A copy of the array is NOT created in the method. public int searchMinimum(float[] number) { int indexOfMinimum = 0; for (int i = 1; i < number.length; i++) { if (number[i] < number[indexOfMinimum]) { //found a indexOfMinimum = i; //smaller element } } return indexOfMinimum; }
In Java, data may be organized in a two-dimensional array. A table is an example of a two-dimensional array. In a two-dimensional array, two indices (in a table, one for the row and one for the column) are used to refer to the array element.
payScaleTable = new double[4][5]; is really a shorthand for payScaleTable = new double[4][ ]; payScaleTable[0] = new double[5]; payScaleTable[1] = new double[5]; payScaleTable[2] = new double[5]; payScaleTable[3] = new double[5]; which is equivalent to payScaleTable = new double[4][ ]; for (int i = 0; i < 4; i++) { payScaleTable[i] = new double[5]; }
The concept of the two-dimensional array in Java is just that: a concept. There is no explicit structure called the “two-dimensional array” in Java. The two-dimensional array concept is implemented by using an array of arrays.
An array that is part of another array is called a subarray. An array of arrays may be initialized when it is created.
One Java interface we have seen is the ActionListener interface. The declaration for an interface includes the reserved word 'interface'. In the declaration, we list the method headers (i.e. a method without body) only.
A list being linear means the object, or elements, in the list are positioned in a linear sequence. That is, l0 is the first element, l1 is the second element, and so forth. A list has not size limit; there is no set limit to the number of elements we can add to a list.
There are total of 25 methods defined in the List interface. The five listed here are the very frequently used subset of those 25 methods.
Because both the ArrayList and LinkedList classes implement the same interface, we know that instances of ArrayList and LinkedList behave the same way, i.e., they support the same set of public methods defined in the List interface.
We can add to, remove from, and retrieve objects in a given list. A list does not have a set limit to the number of objects we can add to it.
There are total of 14 methods defined in the List interface. The five listed here are the very frequently used subset of these 14 methods.
The (key, value) pair for this sample map is the course number and the course title, respectively.
Please use your Java IDE to view the source files and run the program.
Here's the pseudocode to locate a person with the designated name. Notice that for this routine to work correctly, the array must be packed with the real pointers in the first half and null pointers in the last half.
Here's the pseudocode to delete a person with the designated name. First we locate the person. If the person is not found, we exit the delete routine. If the person is found, then we remove it and fill the hole.