Arrays: Declaration, Bounds Checking, and Capacity
E N D
Presentation Transcript
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
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: definition • Array • is a powerful construct used to group and organize data • manages a large amount of information • such as a list of 100 names • it is not logical to declare separate variables in this case • declares one variable • Holding multiple, individually accessible values
The entire array has a single name Each value has a numeric index 79 87 94 82 67 98 87 81 74 91 height Arrays • An array is an ordered list of values 0 1 2 3 4 5 6 7 8 9 • Array indices always begin at zero • An array of size N is indexed from zero to N-1 • This array holds 10 values that are indexed from 0 to 9
Accessing array elements • A particular value in an array • is referenced using the array name • followed by the index in brackets • Example: height[2] refers to the value 94 • height[2] referred to as array element • represents a single integer stored at a memory location • Can be used wherever an integer variable can be used
Manipulating array elements • An array element • Can be assigned a value, printed, or used in calculation height[2] = 89; height[first] = height[first] + 2; mean = (height[0] + height[1])/2; System.out.println ("Top = " + height[5]);
Array elements • Values stored in an array are called array elements • An array stores multiple values of the same type • Called the element type • The element type can be • Primitive type or • Object reference • Therefore, we can create • An array of integers, characters, or String objects
79 87 94 82 67 98 87 81 74 91 Declaring arrays 0 1 2 3 4 5 6 7 8 9 • In Java, the array is an object • It must be declared and instantiated as follows • int[] height = new int[10]; • The type of variable height is an array of integers (int [ ]) • And reference variable heightis set to a new array object • that holds 10 integers • Refer to BasicArray.java height
Declaring Arrays • The scores array could be declared as follows: int[] scores = new int[10]; • The type of the variable scores • is int[] (an array of integers) • Note that the array type • does not specify its size, • but each object of that type has a specific size • The reference variable scores • is set to a new array object that can hold 10 integers
Declaring Arrays • Some other examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];
Using Arrays • The iterator version of the for • loop can be used when processing array elements for (int score : scores) System.out.println (score); • This is only appropriate when • processing all array elements • from top (lowest index) to bottom (highest index)
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
Bounds checking • Once an array is created, it has a fixed size N • int[ ] height = new int[10]; • => size of height = 10 • An index used must specify a valid element • That is, index value must be in the range of 0 to N-1 • The valid indexes for height are from 0 to 9 • In other words, height[10], height[11], … are not allowed
Automatic bounds checking • Whenever you reference an element in the array • => the value of index used is checked • Example: height[index] => index is checked • if 0<= index <= 9 => valid • if index > 9 => index not valid (out of bound) • If an array index is out of bound • An out-of -bound exception is issued by the execution • This is called automatic bounds checking • Refer to Invalidindex.java
problem Off-by-one errors • For example, • if the array codes can hold 100 values • it can be indexed using only the numbers 0 to 99 • If the value of count is 100, • then the following reference will cause an exception to be thrown: System.out.println (codes[count]); • It’s common to introduce off-by-one errors • when using arrays for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;
Length constant • One way to check for the bounds of an array • use the length constant • Each array has a public constant called length • That stores the size of the array • It is referenced using the array name • The array Prices created with 25 elements • Prices.length contains the value 25 • maximum index of Prices is Prices.length - 1
The length constant • Note • That length • holds the number elements • NOT the largest index • Useful in situations where you don’t know the size of the array • Refer to ReverseOrder.java • Read a list of numbers from the user • Store them in an array • Then print them in the opposite order
Alternate array syntax • When declaring an array, the brackets can either • be associated with the type of values stored in the array • float[] prices; • or with the name of array • float prices[]; • These 2 declarations are equivalent • However, the first format • Associating brackets with the type • is more readable and should be used
Initializer lists • Initializer lists • are used to instantiate an array • And provide initial values for the elements of the array • => The idea is to instantiate and fill the array in one step • Values delimited by braces and separated by commas • When used, the new operator will no more be needed • Size of array determined by the number of items in initializer
Initializer lists: Examples • Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'}; • Note that when an initializer list is used • The new operator is not used • no size value is specified • As size is determined by the number of items in the list • See Primes.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
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