Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring...

28
Chapter 7 Arrays: Part 2

Transcript of Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring...

Page 1: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

Chapter 7

Arrays: Part 2

Page 2: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 2/27

Outline

Declaring and Using Arrays

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Page 3: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 3/27

Variable Length Parameter Lists

• Suppose we wanted to create a method that processed a different amount of data from one invocation to the next

• For example, let's define a method called average that returns the average of a set of integer parameters

// one call to average three valuesmean1 = average (42, 69, 37);

// another call to average seven valuesmean2 = average (35, 43, 93, 23, 40, 21, 75);

Page 4: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 4/27

Variable Length Parameter Lists

• We could define overloaded versions of the average method

Downside: we'd need a separate version of the method for each parameter count

• We could define the method to accept an array of integers

Downside: we'd have to create the array and store the integers prior to calling the method each time

Array sizes are also fixed; implies potential wasted storage

Instead, Java provides a convenient way to create variable length parameter lists

Page 5: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 5/27

Variable Length Parameter Lists

• Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type

• For each call, the parameters are automatically put into an array for easy processing in the method

public double average (int ... list){ // whatever} element

typearrayname

Indicates a variable length parameter list

Page 6: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 6/27

Variable Length Parameter Listspublic double average (int ... list){ double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result;}Here, ‘num’ is created to be an int and to assist in traversing the elements of the list: one at a time…

An aside: (Note: for a string, we have a method string.length() An array: length ‘attribute’ – list.length))

Iterator object itself. Here, list is array of ints list of ints is put into an array, an object.

Index to traverse Object or primitive

Index to Object (array of ints here)

Page 7: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 7/27

Variable Length Parameter Lists• The type of the parameter can be any primitive

(shown in previous slide) or object type (shown in this slide)

public void printGrades (Grade ... grades){ for (Grade letterGrade : grades) System.out.println (letterGrade);}

Here, Grade is the class and letterGrade is an item that facilitates stepping through the array of objects, grades. Since this is a System.out.println (letterGrade) we are using the toString method of object, grades.We are also using the iterator form of the ‘for’.This also assumes that an array of Grades(i.e.grades)has already been built, etc.

Page 8: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 8/27

//********************************************************************// GradeRange.java Author: Lewis/Loftus//// Demonstrates the use of an array of objects.//********************************************************************

public class GradeRange{ //----------------------------------------------------------------- // Creates an array of Grade objects and prints them. //----------------------------------------------------------------- public static void main (String[] args) Note: driver. { Grade[] grades = // creating an array of pointers to grades followed by { // the actual creation of 12 grade objects…. (Initializer list) new Grade("A", 95), new Grade("A-", 90), new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80), new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70), new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60), new Grade("F", 0) }; // Note: could have read these in from a file (which we haven’t had yet…)

for (Grade letterGrade : grades) // Here, using iterator form of the ‘for’, we System.out.println (letterGrade); // are printing grades using Grade toString } // Can see that after initializing the array

} // grades, we are merely printing them out.

Page 9: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 9/27

// Grade.java Author: Lewis/Loftus Represents a school grade.public class Grade{ private String name; private int lowerBound; // Constructor: Sets up this Grade object w/specified grade name and numeric lower bound. public Grade (String grade, int cutoff) // Used to initialize each of the twelve grade objects. { name = grade; lowerBound = cutoff; } // Returns a string representation of this grade. public String toString() // Used a lot in next slide. Print out individual grades… { return name + "\t" + lowerBound; } // Name mutator. public void setName (String grade) { name = grade; } // Lower bound mutator. public void setLowerBound (int cutoff) { lowerBound = cutoff; } // Name accessor. public String getName() { return name; } // Lower bound accessor. public int getLowerBound() { return lowerBound; }}

Page 10: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 10/27

Variable Length Parameter Lists

• A method that accepts a variable number of parameters can also accept other parameters

• The following method accepts an int, a String object, and a variable number of double values into an array called nums

public void test (int count, String name, double ... nums){ // whatever}

Page 11: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 11/27

Variable Length Parameter Lists

• The varying number of parameters must come last in the formal arguments

• A single method cannot accept two sets of varying parameters

• Constructors can also be set up to accept a variable number of parameters

• See VariableParameters.java • See Family.java

Page 12: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 12/27

//********************************************************************// VariableParameters.java Author: Lewis/Loftus//// Demonstrates the use of a variable length parameter list.//********************************************************************

public class VariableParameters{ //----------------------------------------------------------------- // Creates two Family objects using a constructor that accepts // a variable number of String objects as parameters. //----------------------------------------------------------------- public static void main (String[] args) { Family lewis = new Family ("John", "Sharon", "Justin", "Kayla");

Family camden = new Family ("Stephen", "Annie", "Matt", "Mary", "Simon", "Lucy", "Ruthie", "Sam", "David");

System.out.println(lewis); // Note: passing object as parameter System.out.println(); // implies a toString method in Family. System.out.println(camden); } // end main()} // end class VariableParameters

Page 13: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 13/27

// Family.java Author: Lewis/Loftus// Demonstrates the use of variable length parameter lists.//********************************************************************public class Family{ private String[] members; //----------------------------------------------------------------- // Constructor: Sets up this family by storing the (possibly // multiple) names that are passed in as parameters. //----------------------------------------------------------------- public Family (String ... names) { members = names; }

//----------------------------------------------------------------- // Returns a string representation of this family. //----------------------------------------------------------------- public String toString() { String result = "";

for (String name : members) result += name + "\n"; What does this do? return result; } // end toString()} // end Family

Page 14: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 14/27

Outline

Declaring and Using Arrays

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Page 15: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 15/27

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

onedimension

twodimensions

Page 16: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 16/27

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];

You may interpret this as an array of 12 rows and 50 columns

(short, fat…) or 12 arrays each w/50 elements

• An array element is referenced using two indices:

value = scores[3][6]

The array stored in one row can be specified using one index (very important!) (scores[3] is a 1d array with six elements in the row.)

Page 17: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 17/27

Two-Dimensional Arrays

Expression Type Description

table int[][] 2D array of integers, orarray of integer arrays

table[5] int[] array of integers

table[5][12] int a specific integer value…

• See TwoDArray.java (page 399)

• See SodaSurvey.java (page 400)

Page 18: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 18/27

public class TwoDArray{ //----------------------------------------------------------------- // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. //----------------------------------------------------------------- public static void main (String[] args) { int[][] table = new int[5][10];

// Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) // in case each row is not 10 items table[row][col] = row * 10 + col; //What is being loaded into table elements? // Print the table for (int row=0; row < table.length; row++) { for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); } // end for } // end main() } // end TwoDArray

Make sure you totallyunderstand what is going on here…

Page 19: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 19/27

// Demonstrates the use of a two-dimensional array.import java.text.DecimalFormat;public class SodaSurvey{ // Determines and prints the average of each row (soda) and each // column (respondent) of the survey scores. public static void main (String[] args) { int[ ][ ] scores = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4}, Here, loading array with hard-coded values… {2, 4, 3, 4, 3, 3, 2, 1, 2, 2}, Note: initializing a two dimensional array.

{3, 5, 4, 5, 5, 3, 2, 5, 5, 5}, {1, 1, 1, 3, 1, 2, 1, 3, 2, 4} }; final int SODAS = scores.length; See problem description in text to understand problem. final int PEOPLE = scores[0].length;

int[] sodaSum = new int[SODAS]; int[] personSum = new int[PEOPLE];

for (int soda=0; soda < SODAS; soda++) for (int person=0; person < PEOPLE; person++) { sodaSum[soda] += scores[soda][person]; personSum[person] += scores[soda][person]; } DecimalFormat fmt = new DecimalFormat ("0.#"); System.out.println ("Averages:\n");

for (int soda=0; soda < SODAS; soda++) System.out.println ("Soda #" + (soda+1) + ": " + fmt.format ((float)sodaSum[soda]/PEOPLE));

System.out.println (); for (int person =0; person < PEOPLE; person++) System.out.println ("Person #" + (person+1) + ": " + fmt.format ((float)personSum[person]/SODAS)); } // end main()} // end SodaSurvey

Page 20: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 20/27

Multidimensional Arrays

• An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array

• Each dimension subdivides the previous one into the specified number of elements

Each dimension has its own length constant

• Because each dimension is an array of array references, the arrays within one dimension can be of different lengths

these are sometimes called ragged arrays

Page 21: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 21/27

Here is an example of a ragged array. It has five rows; Equivalently, it is five single-dimensional arrays – each having a different number of elements.

If array were called junk, we could pass junk[0] or junk[4] to another method for processing. Both junk[0] and junk[4] are both arrays but have different lengths.Hence the entire array, junk, is said to be a “ragged array.”

If the number of columns were the same above, the array would not be considered ‘ragged’ rather, it would be rectangular.

junk[0]

junk[3]

Page 22: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 22/27

Outline

Declaring and Using Arrays

Arrays of Objects

Variable Length Parameter Lists

Two-Dimensional Arrays

The ArrayList Class

Page 23: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 23/27

The ArrayList Class• The ArrayList class is part of the java.util

package

• Like an array, it can store a list of values and reference each one using a numeric index

However, you cannot use the bracket syntax with an ArrayList object

• Furthermore, an ArrayList object grows and shrinks as needed, adjusting its capacity as necessary.

Thus we do NOT need an increaseSize() method as we have done in the past!

This is a super nice feature of Java (C does not have this!)

This is called ‘dynamic storage allocation.” Remember this.

Page 24: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 24/27

The ArrayList Class

• Elements can be inserted or removed with a single method invocation

• When an element is inserted, the other elements "move aside" to make room

• Likewise, when an element is removed, the list "collapses" to close the gap

• The indexes of the elements adjust accordingly

You will be using this in Data Structures.

Page 25: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 25/27

ArrayList – more

• Because the ArrayList is a class in the API, we ‘inherit’ many nice properties.

• Methods such as an initial Constructor ArrayList() boolean add (Object obj) // adds object to end of list void add (int index, Object obj) void clear() Object remove (int index) Object get (int index) boolean isEmpty() int size() and more!

• So once we define an ArrayList, we can use these methods automatically on the array.

Page 26: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 26/27

The ArrayList Class

We can also define an ArrayList object to accept a particular type of object

• The following declaration creates an ArrayList object that only stores Family objects

ArrayList <Family> reunion = new ArrayList<Family>

• This is an example of generics, which are discussed further in Chapter 12

Page 27: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 27/27

// Beatles.java Author: Lewis/Loftus// Demonstrates the use of a ArrayList object.import java.util.ArrayList;

public class Beatles{ // Stores and modifies a list of band members. public static void main (String[] args) { ArrayList band = new ArrayList(); // Constructor automatically invoked. band.add ("Paul"); // add(Object obj) is inherited band.add ("Pete"); band.add ("John"); band.add ("George");

System.out.println (band);

int location = band.indexOf ("Pete"); // indexOf (Object obj) is inherited also) band.remove (location);

System.out.println (band); System.out.println ("At index 1: " + band.get(1));

band.add (2, "Ringo"); // overloaded version of add also inherited. System.out.println (band); System.out.println ("Size of the band: " + band.size()); } // end main()} // end Beatles

Page 28: Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length.

© 2004 Pearson Addison-Wesley. All rights reserved 28/27

ArrayList Efficiency

• The ArrayList class is implemented using an underlying array

• The array is manipulated so that indexes remain continuous as elements are added or removed

• If elements are added to and removed from the end of the list, this processing is fairly efficient

• But as elements are inserted and removed from the front or middle of the list, the remaining elements are shifted and this tends to become somewhat inefficient.