Download presentation
Presentation is loading. Please wait.
1
Arrays, 2-D Arrays, and ArrayList
2
Objectives Learn about arrays and when to use them
Learn the syntax for declaring and initializing arrays and how to access array’s size and elements Learn about the java.util.ArrayList class Discuss “for each” loops Learn simple array algorithms Understand two-dimensional arrays
3
Arrays Array – memory blocks consisting of several consecutive memory locations of the same data type under the same name. Elements – individual memory locations. Size or length - number of elements Index or subscript – element’s number
4
What is an Array An array is a block of consecutive memory locations that hold values of the same data type. Individual locations are called array’s elements. When we say “element” we often mean the value stored in that element. There is indeed some confusion in the usage of “element.” In some situations, the word refers to the location in an array, as in “set the value of the k-th element.” In other situations it refers to a value stored in the array, as in “find the smallest element.” This dual usage is somewhat similar to the situation with the term “variable.” This is no big deal, as long as everyone understands the difference between a location and a value stored in it. An array of doubles 1.39 1.69 1.74 0.0
5
What is an Array (cont’d)
Rather than treating each element as a separate named variable, the whole array gets one name. Specific array elements are referred to by using array’s name and the element’s number, called index or subscript. The idea is not to save names, of course, but to be able to handle an array’s elements uniformly, using algorithms. 1.39 1.69 1.74 0.0 c is array’s name c[0] c[1] c[2] c[3]
6
Indices (Subscripts) In Java, an index is written within square brackets following array’s name (for example, a[k]). Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1]. An index can have any int value from 0 to array’s length - 1. The convention of starting indices from 0 comes from C. It is easy to get used to.
7
Indices (cont’d) We can use as an index an int variable or any expression that evaluates to an int value. For example: a [3] a [k] a [k - 2] a [ (int) (6 * Math.random()) ] That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms.
8
Indices (cont’d) In Java, an array is declared with fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws ArrayIndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1. arr = new int[newSize]; does not really resize arr: it simply throws away the old array and allocates a new one filled with default values. “Throws an exception” means reports a run-time error with rather detailed information about where in the code it occurred and then aborts the program.
9
Why Do We Need Arrays? The power of arrays comes from the fact that the value of a subscript can be computed and updated at run time. No arrays: With arrays: int sum = 0; sum += score0; sum += score1; … sum += score999; int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; Without arrays it would be difficult to process a collection of items algorithmically. Difficult but possible: with linked lists (Chapter 20). 1000 times!
10
Why Arrays? (cont’d) Arrays give direct access to any element — no need to scan the array. No arrays: With arrays: if (k == 0) display (score0); else if (k == 1) display (score1); else … // etc. display (scores[k]); 1000 times! “Direct access” means you can go directly to where the item is stored (like a particular track on a CD), as opposed to scanning from the beginning to find an item (as on a tape).
11
Advantages Allows you to store many values of the same type.
Allows you to manipulate large quantities of data of the same type. Makes coding easier
12
Arrays as Objects In Java, an array is an object. If the type of its elements is anyType, the type of the array object is anyType[ ]. Array declaration: anyType [ ] arrName; This has several implications: you have to create (initialize) an array before you can use it, an array is passed to methods as a reference, etc. You can pass an array to any method that expects an Object type of argument. If you want to test it, try: Object x = new int[100];
13
Arrays as Objects (cont’d)
As with other objects, the declaration creates only a reference, initially set to null. An array must be created before it can be used. One way to create an array: arrName = new anyType [length] ; Brackets, not parens! The second way is show later, on Slide 12-14
14
Declaring Arrays Java treats arrays as objects of the data type that it is declared as. Declaring Arrays DataType name[]; int sum[]; Declaring more than one Array DataType [] name1, name2; String [] first, last; Same as String first[], last[]; Arrays in Java are treated as objects
15
Alternate Array Syntax
The brackets of the array type can be associated with the element type or with the name of the array Therefore the following two declarations are equivalent: float[] prices; float prices[]; The first format generally is more readable and should be used
16
Declaring & Creating Arrays
Use the new operator Example: int score[] = new int[10]; String words[] = new String[12]; Notice the bracket is used instead of parentheses. Number in brackets indicates the size of the array.
17
Arrays declaring and creating
When an array is created, its elements are initialized to default values. (0 –Numeric, false – boolean, null - objects) If the array elements are of that type, then the array contains references to objects of that type and they are initialized to null Once an array is declared and initialized, it is not possible to change its size. You can only reassign its name to another array and throw away the first one.
18
Explicitly Declaring and Creating an Array
Another way to declare and create an array is to list explicitly, between braces, the values of all its elements. The new operator is not used in this form. Example: int scores[] = {95, 56, 76, 58}; String name[] = {“Bob”, “Sue”, “Sam”};
19
Arrays An array is an ordered list of values 0 1 2 3 4 5 6 7 8 9
scores The entire array has a single name Each value has a numeric index An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9
20
Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) That expression represents a place to store a single integer and can be used wherever an integer variable can be used
21
Arrays For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]);
22
Arrays The values held in an array are called array elements
An array stores multiple values of the same type – the element type The element type can be a primitive type or an object reference Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. In Java, the array itself is an object that must be instantiated
23
Arrays Another way to depict the scores array: scores 79 87 94 82 67
98 81 74 91
24
int[] scores = new int[10];
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
25
Declaring Arrays Some other examples of array declarations:
float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];
26
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)
27
Declaration and Initialization
When an array is created, space is allocated to hold its elements. If a list of values is not given, the elements get the default values. For example: length 10, all values set to 0 As for fields: 0 for numbers, false for booleans, null for objects. The elements get default values even if an array is a local variable. You can think of an array’s elements as sort of like its “fields.” scores = new int [10] ; words = new String [10000]; length 10000, all values set to null
28
Initialization (cont’d)
An array can be declared an initialized in one statement. For example: int [ ] scores = new int [10] ; private double [ ] gasPrices = { 3.05, 3.17, 3.59 }; String [ ] words = new String [10000]; String [ ] cities = {"Atlanta", "Boston", "Cincinnati" }; Nothing new here: this is true for any object.
29
Initialization (cont’d)
Otherwise, initialization can be postponed until later. For example: Not yet initialized String [ ] words; ... words = new String [ console.readInt() ]; private double[ ] gasPrices; … gasPrices = new double[ ] { 3.05, 3.17, 3.59 }; Not yet initialized If you try to use an unititialized array, (for example, arr.length or arr[k]), you will get a NullPointerException. The second initialization form (for gasPrices) is not in the AP subset.
30
Initializing Elements
Unless specific values are given in a {…} list, all the elements are initialized to the default value: 0 for numbers, false for booleans, null for objects. If its elements are objects, the array holds references to objects, which are initially set to null. Each object-type element must be initialized before it is used. It is important to understand this two-step process for initializing an array of objects: first you create the array object as a whole; then you initialize each element.
31
Access array’s elements using indices
A program can access individual elements of an array using indices(subscripts). An index is an integer value placed in square brackets after the array name to indicate the consecutive number of the element. In Java arrays are numbered starting at 0. Example: int num[] = {5,6,7,8}; 5 is in the 0 position num[0]; 6 is in the 1st position num[1]; 7 is in the 2nd position num[2]; 8 is in the 3rd position num[3];
32
Accessing arrays y 8 int num[] = {5,6,7,8}; int x = 2;
int y = num[x]; y 7 Or y = num[x+1]; y 8
33
Access array’s length In arrays, length is not a method (as in the String Class). It is accessed like a field , without parenthesis. Example: int nums[] = {1,2,3,4}; int y = nums.length; y 4
34
Length All indices must fall in the range from 0 to length – 1, where length is the number of elements in the array. If an index happens to be out of this range, your program will report a run-time error (IndexOutOfBoundsException)
35
Pass arrays to methods Arrays are not immutable objects.
You can set any elements in an array with a simple assignment statement. Like other Java objects, arrays are always passed to methods as references. If an array is passed to a method, the method gets the address of the original array and works with the original array, not a copy.
36
Examples of passing Arrays
Methods Signatures public void swap(int x[]) Call Obj.swap(nameOfArray);//no brackets
37
Array’s Length The length of an array is determined when that array is created. The length is either given explicitly or comes from the length of the {…} initialization list. The length of an array arrName is referred to in the code as arrName.length. length is like a public field (not a method) in an array object. As opposed to String, where length() is a method.
38
Passing Arrays to Methods
As other objects, an array is passed to a method as a reference. The elements of the original array are not copied and are accessible in the method’s code. // Swaps a [ i ] and a [ j ] public void swap (int [ ] a, int i, int j) { int temp = a [ i ]; a [ i ] = a [ j ]; a [ j ] = temp; } So a void method can do all kinds of things to an array passed to it as a parameter.
39
Returning Arrays from Methods
As any object, an array can be returned from a method. The returned array is usually constructed within the method or obtained from calls to other methods. The return type of a method that returns an array with someType elements is designated as someType[ ]. It is helpful to think of someType[] as a data type designation, “array of someType elements.”
40
Returning Arrays from Methods (cont’d)
public double[ ] solveQuadratic (double a, double b, double c) { double d = b * b - 4 * a * c; if (d < 0) return null; d = Math.sqrt(d); double[ ] roots = new double[2]; roots[0] = (-b - d) / (2*a); roots[1] = (-b + d) / (2*a); return roots; } Or simply: return new double[ ] { (-b - d) / (2*a), (-b + d) / (2*a) }; Since any type of reference can be set to null, it is legal to return null from a method that is supposed to return an array. This means the array has not been created in the method (not to be confused with an array that has been created but whose elements are set to null). Again, the form with a list of values in braces {...}, called “anonymous initialized array,” is not in the AP subset.
41
Inserting a Value (cont’d)
1. Find the right place to insert: 2. Shift elements to the right, starting from the last one: 3. Insert the value in its proper place: 5 Can be combined together in one loop: look for the place to insert while shifting. 1 1 2 3 8 13 5 1 1 2 3 8 13 When an element is removed, the subsequent elements are shifted to the left, starting from the leftmost. 1 1 2 3 5 8 13
42
Inserting a Value (cont’d)
// Returns true if inserted successfully, false otherwise public boolean insert(double[ ] arr, int count, double value) { if (count >= arr.length) return false; int k = count - 1; while ( k >= 0 && arr [ k ] > value ) arr [ k + 1 ] = arr [ k ]; k--; } arr [ k + 1] = value; return true; Or it could just throw an IndexOutOfBoundsException if the array is full.
43
Bounds Checking Once an array is created, it has a fixed size
An index used in an array reference must specify a valid element That is, the index value must be in range 0 to N-1 The Java interpreter throws an ArrayIndexOutOfBoundsExceptio n if an array index is out of bounds This is called automatic bounds checking
44
Bounds Checking 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 problem for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon;
45
Bounds Checking Each array object has a public constant called length that stores the size of the array It is referenced using the array name: scores.length Note that length holds the number of elements, not the largest index
46
Initializer Lists An initializer list can be used to instantiate and fill an array in one step The values are delimited by braces and separated by commas Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
47
Initializer Lists Note that when an initializer list is used:
the new operator is not used no size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can be used only in the array declaration
48
Arrays as Parameters An entire array can be passed as a parameter to a method Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other Therefore, changing an array element within the method changes the original An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type
49
System.out.println (words[0]);
Arrays of Objects The words array when initially declared: words - At this point, the following reference would throw a NullPointerException: System.out.println (words[0]);
50
String[] words = new String[5];
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]; It does NOT create the String objects themselves Initially an array of objects holds null references Each object stored in an array must be instantiated separately
51
Arrays of Objects After some String objects are created and stored in the array: “friendship” words - “loyalty” “honor”
52
Arrays of Objects Keep in mind that String objects can be created using 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"};
53
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);
54
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 Instead, Java provides a convenient way to create variable length parameter lists
55
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 Indicates a variable length parameter list public double average (int ... list) { // whatever } array name element type
56
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;
57
Variable Length Parameter Lists
The type of the parameter can be any primitive or object type public void printGrades (Grade ... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); }
58
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 }
59
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
60
2-D Arrays
61
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 two dimensions one dimension
62
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]; A array element is referenced using two index values: value = scores[3][6] The array stored in one row can be specified using one index
63
Two-Dimensional Arrays
Expression Type Description table int[][] 2D array of integers, or array of integer arrays table[5] int[] array of integers table[5][12] int integer
64
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
65
2-D Arrays 2-D arrays are used to represent rectangular tables of elements of the same type.
66
Declare a 2-D Array Two ways to declare a 2-D array
int name[][] = new int[5][4]; int name[][] = {{1,2,3},{4,5,6}}; The first set of brackets represents the row and the second set of brackets represents the column. The 2-D array is set to the default values if not initialized.
67
Accessing a 2-D Array We access the elements of a 2-D array with a pair of indices, each placed in square brackets. We can think of the first index as a “row” and the second as a “column”. Both indices start from 0. Example: int arr[][] ={{1,2,3},{4,5,6}}; Then arr[0][0] =1;arr[0][1] = 2; arr[0][2] = 3; arr[1][0] = 4; arr[1][1] = 5;arr[1][2] = 6;
68
Length of a 2-D array If m is a 2-D array, then m.length is the number of rows in the array, m[0] is the first row (a 1-D array), and m[0].length is the number of columns(in the first row). m[r][c] is the element in row r and column c. You can also declare a 3-D array the same way as a 2-D array.
69
Two-Dimensional Arrays
2-D arrays are used to represent tables, matrices, game boards, images, etc. An element of a 2-D array is addressed using a pair of indices, “row” and “column.” For example: board [ r ] [ c ] = 'x'; For some reason, 2-D arrays have been excluded from the AP-A subset. They remain in the AP-AB subset.
70
2-D Arrays: Declaration
// 2-D array of char with 5 rows, 7 cols: char[ ] [ ] letterGrid = new char [5][7]; // 2-D array of Color with 1024 rows, 768 cols: Color[ ] [ ] image = new Color [1024][768]; // 2-D array of double with 2 rows and 3 cols: double [ ] [ ] sample = { { 0.0, 0.1, 0.2 }, { 1.0, 1.1, 1.2 } }; It is simply a convention that the first index is “row” and the second “column.”
71
2-D Arrays: Dimensions In Java, a 2-D array is basically a 1-D array of 1-D arrays, its rows. Each row is stored in a separate block of consecutive memory locations. If m is a 2-D array, then m[k] is a 1-D array, the k-th row. m.length is the number of rows. m[k].length is the length of the k-th row. Nothing unusual: an array of rows contains objects; each object happens to be an array.
72
Dimensions (cont’d) Java allows “ragged” arrays, in which different rows have different lengths. In a rectangular array, m[0].length can be used to represent the number of columns. “Ragged” array: Rectangular array: Ragged 2-D arrays are not in the AP subset. m.length m.length m[3].length m[0].length
73
2-D Arrays and Nested Loops
A 2-D array can be traversed using nested loops: for (int r = 0; r < m.length; r++) { for (int c = 0; c < m[0].length; c++) ... // process m[ r ][ c ] } Sometimes we need to traverse by column first, then by row.
74
“Triangular” Loops “Transpose a matrix” idiom: int n = m.length;
for (int r = 1; r < n; r++) { for (int c = 0; c < r; c++) double temp = m [ r ][ c ]; m [ r ][ c ] = m [ c ][ r ]; m [ c ][ r ] = temp; } The total number of iterations through the inner loop is: n-1 = n (n - 1) / 2 “Triangular” loops are also used to find duplicate values in a list, and in other algorithms. To find the sum of an arithmetic sequence (n-1), take the average of the first and the last terms and multiply it by the number of terms.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.