310 likes | 325 Views
This chapter delves into array declaration, bounds checking, multidimensional arrays, ArrayList class, and more in Java. Learn how to work with arrays effectively.
E N D
Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class
Arrays of objects • The elements of an array can be object references • The following declaration • reserves space to store 5 references to String objects • String[] words = new String[5]; • Initially, an array of objects holds null references • Each object stored in an array • must be instantiated separately
- words - - - - Initial array of object declaration • The words array when initially declared • String[] words = new String[5];
“friendship” words “loyalty” “honor” - - After a few object creation • After some String objects • are created • and stored in the array
String literals • Keep in mind • String objects can be created using string literals • The following declaration • Creates an array object called verbs • and fills it with four String objects • Created using string literals String[] verbs = {"play", "work", "eat", "sleep"};
Array of objects: application • The following example • Creates an array of Grade objects • Each with • a string representation and • a numeric lower bound • Refer to GradeRange.java, and Grade.java
Command line arguments • The signature of the main method • it takes an array of String objects as a parameter • Ignored so far, let us discuss how it might be useful • The String[] parameter called args • represents command line arguments • provided when the interpreter is invoked • Extra information on CLI is stored in the args
Command line arguments (cont’d) • For example • The following invocation of the interpreter • passes 3 String objects into main • java StateEval pennsylvania texas arizona • These strings are stored • At indexes 0-2 of the array parameter of the main method • See CLI_reading.java and NameTag.java
Arrays as parameters • An entire array • Can be passed as a parameter to a method • In which case • The method may permanently change an element of the array • An individual array element • Can be passed to a method as well • The type of the parameter is the same as element type
Example • Design and implement a method • That accepts an array of integer values • and then calculates the numerical average • of the group of numbers that are stored in the array
Example: solution 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; }
Method Overloading • Method overloading is the process • of giving a single method name multiple definitions • If a method is overloaded, • the method name is not sufficient to determine • which method is being called • The signature of each overloaded method must be unique • The signature includes • the number, type, and order of the parameters
Invocation result = tryMe(25, 4.32) Method Overloading • The compiler determines which method is being invoked by analyzing the parameters float tryMe(int x) { return x + .375; } float tryMe(int x, float y) { return x*y; }
Method Overloading • The println method is overloaded: println (String s) println (int i) println (double d) and so on... • The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);
Variable length parameter lists • Suppose • We want to create a method • That processes a different amount of data • From one invocation to the next • For example, let us design 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);
Possible solutions • define overloaded versions of the average method • Downside: • This requires that we know the max number of parameters • And create a separate version of the method • for each parameter count • define the method to accept an array of integers • Downside • Need to create the array and store integers prior to method call • Instead, Java provides a more convenient way • to create variable length parameter lists
Indicates a variable length parameter list element type array name Syntax of variable length parameter list • Using a special syntax • You can define a method • To accept any number of parameter of the same type • For each method call • The parameters are automatically • Put into an array for easy processing in the method public double average (int ... list) { // whatever }
Variable length parameter list average method 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; }
Type of the multiple parameters • The type of the parameters • can be any primitive or object type public void printGrades (Grade ... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); }
methods accepting a variable number of parameters • 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 public void test (int count, String name, double ... nums) { // whatever }
Variable length parameter lists: example • 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 setup • to accept a variable number of parameters • Refer to VariableParameters.java & Family.java
Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class
one dimension two dimensions Two-dimensional arrays • A one-dimensional array stores a list of element • A two dimensional array • Can be thought of as a table of elements • With rows and columns
Two dimensional arrays: declaration • 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 • An array element • is referenced using two index values • The array stored in one row • Can be specified using one index int[][] scores = new int[12][50]; value = scores[3][6]
Two-dimensional arrays: example • See TwoDArray.java • See SodaSurvey.java
Chapter overview • This chapter focuses on • Array declaration and use • Bounds checking and capacity • Arrays storing object references • Variable length parameter lists • Multidimensional arrays • The ArrayList class
The ArrayList class • The ArrayList class • is part of java.util • Can store a list of values • and reference each one using a numeric index • Dynamically grows and shrinks as needed • Adjusting its capacity as necessary • However, you cannot use the brackets syntax • With an ArrayList object
ArrayList elements • ArrayList • is not declared to store a particular type • any type of object can be added to an ArrayList • stores references to different types of objects • If a primitive value must be stored in an ArrayList • Use the appropriate wrapper class
Arraylist: inserting and removing elements • Elements in an ArrayList • Can be inserted or removed • with a single method invocation • When an element is inserted • Other elements move aside to make room • When an element is removed • The list collapses to close the gap • The indexes of elements adjust accordingly
Specifying an ArrayList element type • See Beatles.java • we can also define • An ArrayList object to accept a particular object type • The following declaration creates an ArrayList object • that only stores Family objects ArrayList<Family> reunion = new ArrayList<Family>
Methods defined in ArrayList • boolean add(Object obj) • Inserts the specified object to the end of the list • object remove(int index) • Removes the element at specified index in the list • void add(int index, Object obj) • Inserts the specified object into list at specified index • int indexOf(Object obj) • Returns the index of 1st occurrence of the specified object