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

Slides:



Advertisements
Similar presentations
Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Advertisements

Arrays.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Wecksten, Mattias Arrays Based on templates from Lewis & Loftus.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Arrays Chapter 7 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses on: array declaration and use passing arrays and array.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
1 Objects for Organizing Data -- b As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array.
1 7 Arrays. 2 Arrays are objects that help us organize large amounts of information Chapter 7 focuses on: –array declaration and use –bounds checking.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Copyright © 2012 Pearson Education, Inc. Chapter 8 Arrays Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 7 Arrays. Chapter Scope Array declaration and use Bounds checking Arrays as objects Arrays of objects Command-line arguments Variable-length parameter.
COS 312 DAY 11 Tony Gauvin. Ch 1 -2 Agenda Questions? One Capstone proposal over due – First Progress report due March 5 (next class) Assignment 3 Not.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
© 2004 Pearson Addison-Wesley. All rights reserved October 13, D Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor:
Chapter 7 Arrays: Part 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Programming in Java (COP 2250) Lecture Chengyong Yang Fall, 2005.
1 Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 7: Arrays.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.
© 2004 Pearson Addison-Wesley. All rights reserved October 15, 2007 Searching ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
© 2004 Pearson Addison-Wesley. All rights reserved October 10, 2007 Parameter Lists & Command Line Arguments ComS 207: Programming I (in Java) Iowa State.
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split()
Arrays.
O BJECTS FOR O RGANIZING D ATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. Chapter 6 focuses on: array.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Chapter VII: Arrays.
COS 312 DAY 14 Tony Gauvin.
Parameter Lists & Command Line Arguments
Chapter 7: Arrays.
The ArrayList Class An ArrayList object stores a list of objects, and is often processed using a loop The ArrayList class is part of the java.util package.
2D Arrays October 12, 2007 ComS 207: Programming I (in Java)
Outline Declaring and Using Arrays Arrays of Objects
Arrays.
Presentation transcript:

Chapter 7 Arrays: Part 2

© 2004 Pearson Addison-Wesley. All rights reserved2/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class

© 2004 Pearson Addison-Wesley. All rights reserved3/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 values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);

© 2004 Pearson Addison-Wesley. All rights reserved4/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

© 2004 Pearson Addison-Wesley. All rights reserved5/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 type array name Indicates a variable length parameter list

© 2004 Pearson Addison-Wesley. All rights reserved6/27 Variable Length Parameter Lists public 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)

© 2004 Pearson Addison-Wesley. All rights reserved7/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.

© 2004 Pearson Addison-Wesley. All rights reserved8/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.

© 2004 Pearson Addison-Wesley. All rights reserved9/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; }

© 2004 Pearson Addison-Wesley. All rights reserved10/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 }

© 2004 Pearson Addison-Wesley. All rights reserved11/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 VariableParameters.java See Family.java Family.java

© 2004 Pearson Addison-Wesley. All rights reserved12/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

© 2004 Pearson Addison-Wesley. All rights reserved13/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

© 2004 Pearson Addison-Wesley. All rights reserved14/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class

© 2004 Pearson Addison-Wesley. All rights reserved15/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 one dimension two dimensions

© 2004 Pearson Addison-Wesley. All rights reserved16/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.)

© 2004 Pearson Addison-Wesley. All rights reserved17/27 Two-Dimensional Arrays ExpressionTypeDescription tableint[][] 2D array of integers, or array of integer arrays table[5]int[] array of integers table[5][12]int a specific integer value… See TwoDArray.java (page 399) TwoDArray.java See SodaSurvey.java (page 400) SodaSurvey.java

© 2004 Pearson Addison-Wesley. All rights reserved18/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 totally understand what is going on here…

© 2004 Pearson Addison-Wesley. All rights reserved19/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

© 2004 Pearson Addison-Wesley. All rights reserved20/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

© 2004 Pearson Addison-Wesley. All rights reserved21/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]

© 2004 Pearson Addison-Wesley. All rights reserved22/27 Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class

© 2004 Pearson Addison-Wesley. All rights reserved23/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.

© 2004 Pearson Addison-Wesley. All rights reserved24/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.

© 2004 Pearson Addison-Wesley. All rights reserved25/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.

© 2004 Pearson Addison-Wesley. All rights reserved26/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 reunion = new ArrayList This is an example of generics, which are discussed further in Chapter 12

© 2004 Pearson Addison-Wesley. All rights reserved27/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

© 2004 Pearson Addison-Wesley. All rights reserved28/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.