270 likes | 432 Views
Chapter 7. Arrays: Part 2. Outline. Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class. Variable Length Parameter Lists.
E N D
Chapter 7 Arrays: Part 2
Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class © 2004 Pearson Addison-Wesley. All rights reserved
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 values mean1 = average (42, 69, 37); This implies average has three formal parameters // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75); This implies average has seven formal parameters. © 2004 Pearson Addison-Wesley. All rights reserved
Variable Length Parameter Lists • We could define overloaded versions of the average method (What does that mean??) • 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 © 2004 Pearson Addison-Wesley. All rights reserved
Indicates a variable length parameter list (note these are the ‘formal’ parameters’) element type array name 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 automaticallyputintoanarray for easy processing in the method public double average (int ... list) { // whatever } © 2004 Pearson Addison-Wesley. All rights reserved
Variable Length Parameter Lists public double average (int ... list) Note formal parameters! { 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 (iterating) through 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 Num is an iterator to the object, list. List is the object itself and it is an array of ints. The list of ints is put into the array, an object. Index to Object (array of ints here) © 2004 Pearson Addison-Wesley. All rights reserved
Variable Length Parameter Lists • The type of the parameter can be a primitive (last slide) or an object type (this slide) Called routine: public void printGrades (Grade ... grades) { // creates an array grades from Grade objects sent to printGrades) for (Grade letterGrade : grades) System.out.println (letterGrade); }// end printGrades() Here, Grade is the class and letterGrade is an item that facilitates stepping through the array of objects, grades. (letterGrade is the iterator) Since this is a System.out.println (letterGrade) we invoke the toString method of object, grades. We are also using the iteratorform of the ‘for’. The programmer sets up this version of the for stmt. © 2004 Pearson Addison-Wesley. All rights reserved
//********************************************************************//******************************************************************** // 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 too for (Grade letterGrade : grades) // Here, using iterator form of the ‘for’, we System.out.println (letterGrade); // are printing grades using Grade toString } // end main() // Can see that after initializing the array } // end class // grades, we are merely printing them out. © 2004 Pearson Addison-Wesley. All rights reserved
// 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; } } © 2004 Pearson Addison-Wesley. All rights reserved
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, andthen a variable number of double values into an array called nums public void test (int count, String name, double ... nums) { // whatever }// end test © 2004 Pearson Addison-Wesley. All rights reserved
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 © 2004 Pearson Addison-Wesley. All rights reserved
//********************************************************************//******************************************************************** // 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 using a toString method in Family. System.out.println(camden); } // end main() } // end class VariableParameters © 2004 Pearson Addison-Wesley. All rights reserved
// 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 © 2004 Pearson Addison-Wesley. All rights reserved
Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class © 2004 Pearson Addison-Wesley. All rights reserved
one dimension two dimensions 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 © 2004 Pearson Addison-Wesley. All rights reserved
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.) © 2004 Pearson Addison-Wesley. All rights reserved
Two-Dimensional Arrays • See TwoDArray.java • See SodaSurvey.java © 2004 Pearson Addison-Wesley. All rights reserved
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 totally understand what is going on here… © 2004 Pearson Addison-Wesley. All rights reserved
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 © 2004 Pearson Addison-Wesley. All rights reserved
junk[0] junk[3] 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.” Can you think of an instance of a ragged array? If the number of columns were the same above, the array would not be considered ‘ragged’ rather, it would be rectangular. © 2004 Pearson Addison-Wesley. All rights reserved
Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class © 2004 Pearson Addison-Wesley. All rights reserved
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 / do not use the bracket syntax with an ArrayList object • Further, 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. © 2004 Pearson Addison-Wesley. All rights reserved
The ArrayList Class • Elements can be inserted or removed with a single method invocation • When an element is inserted at a particular point, the other elements "move aside" to make room • Likewise, when an element is removed, the list "collapses" to close the gap automatically! • The indexes of the elements adjust accordingly • ArrayList is not declared to store a particular type; an arraylist object merely stores a list of references to the Object class, which means that any type of object can be added to an ArrayList. • Because we get this from java.util package, we ‘inherit’ a bunch of methods shown ahead. (Will discuss Object class). • You will be using this in Data Structures. © 2004 Pearson Addison-Wesley. All rights reserved
ArrayList – more • Because the ArrayList is a class in the API, we ‘inherit’ many nice properties. • Methods such as an initial Constructor • ArrayList() (creates an initial empty list) • boolean add (Object obj) // adds object to end of list • void add (int index, Object obj) • void clear() – clears all elements from this list. • Object remove (int index) • Object get (int index) • boolean isEmpty() • int size() returns number of elements in the list. • So once we define an ArrayList, we can use these methods automatically on the array. © 2004 Pearson Addison-Wesley. All rights reserved
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> Declares an array, reunion, of Family objects. © 2004 Pearson Addison-Wesley. All rights reserved
// 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. // could say: ArrayList <String> band = new ArrayList(); // ensures that only objects of type String are added as references… band.add ("Paul"); // add(Object obj) is inherited band.add ("Pete"); band.add ("John"); band.add ("George"); System.out.println (band); // because band is an object, toString() is invoked to print… 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 CAN SEE OUTPUTS IN YOUR BOOK… © 2004 Pearson Addison-Wesley. All rights reserved
ArrayListEfficiency • 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. © 2004 Pearson Addison-Wesley. All rights reserved