Download presentation
Presentation is loading. Please wait.
Published byEmory Rodgers Modified over 9 years ago
1
7. Arrays
2
Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events
3
Arrays An array is an ordered list of values. An array is an ordered list of values. 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 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
4
Array Elements A particular value in an array is referenced using the array name followed by the index in brackets A particular value in an array is referenced using the array name followed by the index in brackets scores[0] // has value of 79 scores[2] // has value of 94 scores[2] = 89; scores[1] = scores[1] + 2; mean = (scores[0] + scores[1])/2.0; System.out.println ("Top = " + scores[5]); scores[0] // has value of 79 scores[2] // has value of 94 scores[2] = 89; scores[1] = scores[1] + 2; mean = (scores[0] + scores[1])/2.0; System.out.println ("Top = " + scores[5]); 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 scores
5
Array Elements Array elements can be of primitive types or references to objects Array elements can be of primitive types or references to objects Array of int; array of String; array of Student; etc. Array of int; array of String; array of Student; etc. Elements must be of same type.. Elements must be of same type.. Java array is an object; it must be instantiated. Java array is an object; it must be instantiated.
6
Array Instantiation Instantiating Integer Array int[] scores = new int[10]; Instantiating Integer Array int[] scores = new int[10]; scores[0] = 79; scores[1] = 87; scores[2] = 94; scores[0] = 79; scores[1] = 87; scores[2] = 94; 79 87 94 scores
7
Array Instantiations float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; final int CLASS_SIZE = 30; String names = new String[CLASS_SIZE]; Student stds = new Students[CLASS_SIZE];
8
For-Loop with Iterator An iterator version of the For-loop allows you to visit each element of the array without knowing its size. An iterator version of the For-loop allows you to visit each element of the array without knowing its size. int[] scores = new int[30]; … for (int num : scores) System.out.println(num); int[] scores = new int[30]; … for (int num : scores) System.out.println(num); BasicArray.java BasicArray.java BasicArray.java
9
Bounds Checking Once an array is created, its size is fixed. final int N = 100; int[] scores = new int[N]; Once an array is created, its size is fixed. final int N = 100; int[] scores = new int[N]; Valid indices: 0.. N-1 Valid indices: 0.. N-1 ArrayIndexOutOfBoundsException exception is thrown when an invalid index is referenced. ArrayIndexOutOfBoundsException exception is thrown when an invalid index is referenced.
10
Bounds Checking Each array has a constant named length that returns the size of an array: for (int i = 0; i < scores.length; i++) { do something with scores[i]; } Each array has a constant named length that returns the size of an array: for (int i = 0; i < scores.length; i++) { do something with scores[i]; } Note: Note: length is the size of the array, not the count of its elements. length is the size of the array, not the count of its elements. length is a variable—not a method length is a variable—not a method ReverseOrder.java (p 377) ReverseOrder.java (p 377) ReverseOrder.java LetterCount.java (p 378) LetterCount.java (p 378) LetterCount.java
11
Array Initialization Array Initialization Array Initialization Note: Note: No array size is specified—It is determined by the number of elements No array size is specified—It is determined by the number of elements There is no key word new in the declaration. There is no key word new in the declaration. Array initialization is allowed only at declaration. Array initialization is allowed only at declaration. Primes.java (p 383) Primes.java (p 383) Primes.java int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
12
Array Parameters When an array is passed as a method parameter, it is passed as a reference. When an array is passed as a method parameter, it is passed as a reference. This means that the actual and formal parameters are aliases of the same object. This means that the actual and formal parameters are aliases of the same object. An object modified in the method is the same object in the calling unit. An object modified in the method is the same object in the calling unit.
13
Outline Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events
14
Array Initialization Assume: Scanner sc = new Scanner(System.in); final int MAX = 100; int[] aList = new int[MAX]; int count = 0; Assume: Scanner sc = new Scanner(System.in); final int MAX = 100; int[] aList = new int[MAX]; int count = 0; Initialize: int n = sc.nextInt(); while(n != -1){ aList[count] = n; count++; n = nextInt(); } Initialize: int n = sc.nextInt(); while(n != -1){ aList[count] = n; count++; n = nextInt(); }
15
Find the Average int sum = 0; for (int i = 0; i < count; i++){ sum += aList[i]; } float ave = (float)sum / count; System.out.println(“Average: “ + ave); int sum = 0; for (int i = 0; i < count; i++){ sum += aList[i]; } float ave = (float)sum / count; System.out.println(“Average: “ + ave);
16
Find the Largest Assume: aList[] contains count elements Assume: aList[] contains count elements int big; big = aList[0]; for (int i = 0; i big) big = aList[i]; } System.out.println(“Largest: “ + big); int big; big = aList[0]; for (int i = 0; i big) big = aList[i]; } System.out.println(“Largest: “ + big);
17
Search for an Item in Array Search for a (key) item and return yes or no. Search for a (key) item and return yes or no. Search for a (key) item and its position in the list Search for a (key) item and its position in the list Search for a (key) item (e.g., ID Num) in a list of Student objects and return the corresponding student. Search for a (key) item (e.g., ID Num) in a list of Student objects and return the corresponding student.
18
Search and Return Position Assume: aList[] contains count elements Assume: aList[] contains count elements int key = 5; boolean found = false; int pos = 0; while (!found && pos < count){ if (key == aList[pos] found = true; else pos++; } if (found) System.out.println(key + “ found at position” + pos”); else System.out.printl(key + “ was not found.”); int key = 5; boolean found = false; int pos = 0; while (!found && pos < count){ if (key == aList[pos] found = true; else pos++; } if (found) System.out.println(key + “ found at position” + pos”); else System.out.printl(key + “ was not found.”);
19
Outline Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events
20
Array of Objects String[] words = new String[5]; String[] words = new String[5]; This creates an array of 5 String elements. This creates an array of 5 String elements. It does NOT create the String elements themselves. It does NOT create the String elements themselves. At this point, the elements contain null values—pointing to “nothing”. At this point, the elements contain null values—pointing to “nothing”.
21
Array of Objects String[] words = new String[5]; System.out.println(words[0]); String[] words = new String[5]; System.out.println(words[0]); The statement will cause NullPointerException. The statement will cause NullPointerException. words - - - - -
22
Instantiating Array Elements words[0] = new String(“friendship”); words[1] = new String(“loyalty”); words[2] = “honor”; words[0] = new String(“friendship”); words[1] = new String(“loyalty”); words[2] = “honor”; “friendship” words - - “loyalty” “honor”
23
Initializing Array of Words Scanner sc = new Scanner(System.in); String[] words = new String[5]; int index = 0; char more = ‘y’; while (more == ‘y’){ System.out.println(“Enter word.”); aWord = sc.next(); words[index] = new String(aWord); index++; System.out.println(“More words (‘y/n’)?”); more = sc.next(); } Scanner sc = new Scanner(System.in); String[] words = new String[5]; int index = 0; char more = ‘y’; while (more == ‘y’){ System.out.println(“Enter word.”); aWord = sc.next(); words[index] = new String(aWord); index++; System.out.println(“More words (‘y/n’)?”); more = sc.next(); }
24
Initializing a String Array String[] names = {new String(“Abe”), new String(“Bess”), new String(“Cal”) }; String[] names = {new String(“Abe”), new String(“Bess”), new String(“Cal”) }; Short cut for Strings String[] names = {“Abe”,“Bess”,“Cal”}; Short cut for Strings String[] names = {“Abe”,“Bess”,“Cal”};
25
Example Programs Grade maintains letter grade and its lower boundary Grade maintains letter grade and its lower boundary GradeRange.java (p 386) GradeRange.java (p 386) GradeRange.java Grade.java (p 387) Grade.java (p 387) Grade.java Collection of CD objects Collection of CD objects Tunes.java (p 389) Tunes.java (p 389) Tunes.java CDCollection.java (p 390) CDCollection.java (p 390) CDCollection.java CD.java (p 393) CD.java (p 393) CD.java
26
Command-Line Arguments class MyClass { public static void main(String[] args){ for (int i = 0; i < args.length; i++) System.out.println(args[i]); } } C:\ java Myclass uno dos tres uno dos tres Command line Output NameTag.java NameTag.java
27
Topics Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events
28
Two-Dimensional Arrays 1-D array is like a list of elements. 1-D array is like a list of elements. 2-D array is like a table. 2-D array is like a table. one dimension two dimensions
29
Two-Dimensional Arrays In Java, 2-D array is an array of array elements. In Java, 2-D array is an array of array elements. int table[][] = new int[10][20]; // 10 rows, 20 cols table[5] // refers to 5 th row // array of 20 elements table[5][12] // int at row 5, col 12 table[5].length // 20 table[9].length // 20 table[10].length // invalid int table[][] = new int[10][20]; // 10 rows, 20 cols table[5] // refers to 5 th row // array of 20 elements table[5][12] // int at row 5, col 12 table[5].length // 20 table[9].length // 20 table[10].length // invalid TwoDArray.java (p 401) TwoDArray.java (p 401) TwoDArray.java SodaSurvey.java (p 42) SodaSurvey.java (p 42) SodaSurvey.java
30
Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events
31
Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList Class Polygons and Polylines Mouse Events and Key Events
32
Outline Declaring and Using Arrays Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays Polygons and Polylines Mouse Events and Key Events
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.