Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types. Data Structure Starting Point Any data type that can store more than one value is a data structure. First Array Definition An array is a data structure with one, or more, elements of the same type. A one-dimensional array is frequently also called a vector. A two-dimensional array is frequently also called a matrix. First Record Definition A record is a data structure with one, or more, elements, called fields, of the same or different data types. File Definition A file is an internal data structure - with an unspecified number of elements of the same type - assigned to an external file name. The file data structure allows transfer of data between internal and external storage. Stack Definition A stack is a data structure with elements of the same type. Data elements of the stack data structure can only be accessed (stored or retrieved) at one end of the stack in a LIFO (Last In, First Out) manner. Improved Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types. The storing and retrieval of the data elements is performed by accessing methods that characterize the data structure. Improved Array Definition An array is a data structure with a fixed number of elements of the same type. Every element of the array can be accessed directly. 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. 1.39 1.69 1.74 0.0 An array of doubles 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. 1.39 1.69 1.74 0.0 c[0] c[1] c[2] c[3] c is array’s name Array Example [16] Ingrid [17] Darlene [18] Gene [19] Sean [20] Stephanie [11] Holly [12] Blake [13] Michelle [14] Remy [15] Haley [06] Diana [07] Jessica [08] David [09] Anthony [10] Alec [01] Isolde [02] John [03] Greg [04] Maria [05] Heidi Defining Static Arrays int list[ ]; list = new int[10]; // declares the array list identifier // allocates memory for 10 integers char names[ ]; names = new char[25]; // declares the names array identifier // allocates memory for 25 characters double grades[ ]; // declares the grades array identifier grades = new double[50]; // allocates memory for 50 doubles Defining Static Arrays Preferred Method int list[ ] = new int[10]; char names[ ] = new char[25]; double grades[ ] = new double[50]; // Java1201.java // This program demonstrates how to declare an array of integers. // Note how each element of the array defaults to zero. // Java allows the display of uninitialized objects because object // elements get assigned values from the default constructor. public class Java1201 { public static void main(String args[]) { int list[]; // declares the array object identifier list = new int[10]; // allocates memory for 10 array elements for (int k = 0; k < 10; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); 0 1 2 3 4 5 6 7 8 9 } 0 0 0 0 0 0 0 0 0 0 } Array Index Note Java arrays indicate individual elements with an index inside two brackets, following the array identifier, like list[k] The array index is always an integer and starts at 0. In an array of N elements, the largest index is N-1. 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. 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()) ] 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. // Java1202.java // This program is almost identical to Java1201. The difference // is that the array declaration and array definition to allocate // memory is done in one program statement. public class Java1202 { public static void main(String args[]) { int list[] = new int[10]; // combined array declaration and definition for (int k = 0; k < 10; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); } } 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 // Java1203.java // This program demonstrates how to initialize array elements. // The <new> operator is not necessary in this case. public class Java1203 { public static void main(String args[]) { int list[] = {11,22,33,44,55,66,77,88,99}; for (int k = 0; k < 9; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); } } 0 1 2 3 4 5 6 7 8 11 22 33 44 55 66 77 88 99 // Java1204.java // This program demonstrates how to declare an array of characters. // Are the array elements initialized to any kind of value? public class Java1204 { public static void main(String args[]) { int k; char list1[] = new char[5]; for (k = 0; k < 5; k++) System.out.println("list1[" + k + "] = " + list1[k]); System.out.println(); char list2[] = {'c','h','a','r'}; for (k = 0; k < 4; k++) System.out.println("list2[" + k + "] = " + list2[k]); System.out.println(); 0 1 2 3 4 0 1 2 3 list1 list2 } ? ? ? ? ? c h a r } // Java1205.java // The purpose of this program is to investigate the type of character // that is used to initialize a character array. // Is it no-character-at-all or a blank space? public class Java1205 { public static void main(String args[]) { char List1[] = new char[10]; System.out.print("Start"); for (int K = 0; K < 10; K++) System.out.print(List1[K]); System.out.println("End"); System.out.println(); } 1 0 2 3 4 5 6 7 8 9 }<sp> <sp> <sp> <sp> <sp> <sp> <sp> <sp> <sp> <sp> // Java1206.java // This program demonstrates how String objects are initialized, // both without and with specified array values. public class Java1206 { public static void main(String args[]) { String list1[] = new String[5]; for (int k = 0; k < 5; k++) System.out.println("list[" + k + "] = " + list1[k]); System.out.println(); String list2[] = {"AAA","BBB","CCC","DDD","EEE"}; for (int k = 0; k < 5; k++) System.out.println("list2[" + k + "] = " + list2[k]); 0 1 2 3 4 0 System.out.println(); 1 2 3 4 list1 } null null null null null list2 AAA BBB CCC DDD EEE } // Java1207.java // This program fills an integer array with a random set of numbers. import java.util.Random; public class Java1207 { public static void main(String args[]) { int list[] = new int[20]; Random random = new Random(12345); for (int k = 0; k < 20; k++) list[k] = random.nextInt(900) + 100; for (int k = 0; k < 20; k++) System.out.println("list[" + k + "] = " + list[k]); System.out.println(); 0 1} 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 } 680 241 928 455 284 575 802 701 889 717 142 890 206 312 584 687 803 851 18 19 432 775 // Java1208.java // This program introduces the length field to determine the // number of elements in the array. Remove the comments from line // 16 to observe what happens when the length field is altered. public class Java1208 { public static void main(String args[]) { String names[] = {"Joe","Tom","Sue","Meg"}; int n = names.length; // data field access; not a method call System.out.println("There are " + n + " array elements."); for(int k = 0; k < n; k++) System.out.println("names[" + k + "] = " + names[k]); // names.length = 10; // Line 16 System.out.println(); } } 0 1 2 3 Joe Tom Sue Meg // Java1209.java // This program demonstrates how to create an array of random strings. import java.util.Random; public class Java1209 { public static void main(String args[]) { Random random = new Random(12345); int rndInt; String names[] = {"AA","BB","CC","DD","EE","FF","GG","HH","II","JJ"}; for(int k = 1; k < 15; k++) { rndInt = random.nextInt(names.length); System.out.println("names[" + rndInt + "] = " + names[rndInt]); } System.out.println(); 0 }AA } 1 2 3 4 5 6 7 8 9 BB CC DD EE FF GG HH II JJ 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: 1000 times! int sum = 0; sum += score0; sum += score1; … sum += score999; With arrays: int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; Why Arrays? (cont’d) • Arrays give direct access to any element — no need to scan the array. 1000 times! No arrays: With arrays: if (k == 0) display (score0); else if (k == 1) display (score1); else … // etc. display (scores[k]); 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; 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. • OnearrName way to=create an array: new anyType [length] ; Brackets, not parens! 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 length 10, default values. For example: scores = new int [10] ; words = new String [10000]; all values set to 0 length 10000, all values set to null 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" }; Initialization (cont’d) • Otherwise, initialization can be postponed until later. For example: String [ ] words; Not yet initialized ... words = new String [ console.readInt() ]; Not yet private double[ ] gasPrices; initialized … gasPrices = new double[ ] { 3.05, 3.17, 3.59 }; 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. 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. Initializing Elements (cont’d) • Example: Array not created yet Color[ ] pens; Array is created; ... all three elements pens = new Color [ 3 ]; are set to null ... pens [0] = Color.BLUE; Now all three pens [1] = new Color (15, 255, 255); elements are pens [2] = g.getColor(); initialized 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; } 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[ ]. 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) }; AP Exam Alert One-dimensional arrays will be tested for the "A-level" and "AB-level" APCS examination. Two-dimensional arrays will only be tested for the "AB-level" APCS examination. java.util.ArrayList<E> • Implements a list using an array. • Can only hold objects (of a specified type), not elements of primitive data types. • Keeps track of the list capacity (the length of the allocated array) and list size (the number of elementscapacity currently in the list) size "Cat" "Hat" "Bat" ... ArrayList Generics • Starting with Java 5, ArrayList and other collection classes hold objects of a specified data type. • The elements’ data type is shown in angle brackets and becomes part of the ArrayList type. For example: ArrayList<String> words = new ArrayList<String>(); ArrayList<Integer> nums = new ArrayList<Integer>(); ArrayList<E> Constructors Java docs use the letter E as the type parameter for elements in generic collections ArrayList<E> ( ) ArrayList<E> (int capacity) Creates an empty ArrayList<E> of the specified capacity Creates an empty ArrayList<E> of default capacity (ten) // Java2004.java // This program introduces the <ArrayList> class with the <add> method // to add additional elements to the end of the list. // Note, that it is possible to display ArrayList elements directly. import java.util.ArrayList; public class Java2004 { public static void main(String args[]) { System.out.println(); System.out.println("Java2004.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add(new String("Heidi")); System.out.println("names contains " + names); System.out.println(); } } ArrayList Access ArrayList objects cannot be accessed with an index [ ] operator, like a Java static array. All access is performed with ArrayList methods. ACCESS DENIED! ArrayList<E> Methods (a Subset) int size() boolean isEmpty () boolean add (E obj) returns true void add (int i, E obj) inserts obj as the i-th value; i must be from 0 to size() E set(int i, E obj) E get(int i) E remove(int i) boolean contains(E obj) int indexOf(E obj) i must be from 0 to size() -1 use equals to compare objects ArrayList Example ArrayList<String> names = new ArrayList<String>( ); names.add("Ben"); names.add("Cat"); names.add(0, "Amy"); System.out.println(names); Output [Amy, Ben, Cat] ArrayList’s toString method returns a string of all the elements, separated by commas, within [ ]. ArrayList Method add names.add("Tom"); The add method allocates space for the newly enlarged array and then stores the new array element at the end of the ArrayList object. Displaying ArrayList Elements ArrayList elements can be accessed with various methods. It is possible to display all the elements inside square brackets, separated by commas by using the print method. System.out.println(names); [Isolde, John, Greg, Maria, Heidi] // Java2005.java // This program uses the <size>method to determine the number of elements // in an <ArrayList object. import java.util.ArrayList; public class Java2005 { public static void main(String args[]) { System.out.println(); System.out.println("Java2005.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add(new String("Heidi")); System.out.println("names contains " + names); System.out.println(); System.out.println("There are " + names.size() + " elements in the names object."); System.out.println(); } } ArrayList Method size int count = names.size(); The size method returns the number of elements of the ArrayList object names. Remember Strings and Java static arrays use length instead of size. // Java2006.java // This program shows how to access specified elements in an <ArrayList> object // with the <get> method. import java.util.ArrayList; public class Java2006 { public static void main(String args[]) { System.out.println(); System.out.println("Java2006.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add(new String("Heidi")); System.out.println(); for (int k = 0; k < names.size(); k++) System.out.println(names.get(k)); System.out.println(); for (int k = names.size()-1; k >= 0; k--) System.out.println(names.get(k)); } } ArrayList Method get System.out.println(names.get(3)); The get method accesses a specified array element. The parameter of the get method is the index of the ArrayList object and starts at 0. Any attempt to access an element at a non-existing index results in an IndexOutOfBoundsException error. // Java2007.java // This program demonstrates the <set> method of the <ArrayList> class, which // replaces existing elements with a new object. import java.util.ArrayList; public class Java2007 { public static void main(String args[]) { System.out.println("Java2007.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names contains " + names); System.out.println(); names.set(1,"Jessica"); names.set(2,"Anthony"); names.set(3,"Haley"); names.set(4,"Alec"); System.out.println("names contains " + names); } } ArrayList Method set names.set(4,"Tom"); The set method uses the first parameter as the index location to find an array element and then replaces it with the value of the second set parameter. You will get an error if you try to access an index location, which has not been allocated yet. // Java2008.java // This program demonstrates the <remove> method of the <ArrayList> class to // delete a specified list element. import java.util.ArrayList; public class Java2008 { public static void main(String args[]) { System.out.println(); System.out.println("Java2008.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names contains " + names); System.out.println(); names.remove(2); System.out.println("names contains " + names); System.out.println(); names.remove(3); System.out.println("names contains " + names); System.out.println(); } } ArrayList Method remove names.remove(3); The remove method removes the array element at the index location of its parameter and decreases the object size by one array element. You will get an error if you try to access an index location, which does not exist. // Java2009.java // This program demonstrates how to use the <add> method of the <ArrayList> class to // insert new elements at a specified location. import java.util.ArrayList; public class Java2009 { public static void main(String args[]) { System.out.println("Java2009.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names contains " + names); System.out.println(); names.add(2,"Jessica"); System.out.println("names contains " + names); System.out.println(); names.add(3,"Anthony"); System.out.println("names contains " + names); } } ArrayList Method add nd (2 Overloaded method) names.add(3,"Kathy"); The overloaded add(3,"Kathy") method adds or rather inserts a new array element at the indicated index. As always, you will get an error if you try to access an index location, which does not exist. // Java2010.java // This program demonstrates how to use the <clear> method to remove all the // array elements and the <isEmpty> method to check if emptiness is true. import java.util.ArrayList; public class Java2010 { public static void main(String args[]) { System.out.println(); System.out.println("Java2010.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names contains " + names); System.out.println("Empty list is " + names.isEmpty()); names.clear(); System.out.println(); System.out.println("names contains " + names); System.out.println("Empty list is " + names.isEmpty()); System.out.println(); } } ArrayList<E> Details • Automatically increases (doubles) the capacity when the list runs out of space (allocates a bigger array and copies all the values into it). • get(i) and set(i, obj) are efficient because an array provides random access to its elements. • Throws IndexOutOfBoundsException when i < 0 or i size() (or i > size() in add (i, obj) ) ArrayList<E> Autoboxing • If you need to put ints or doubles into a list, use a standard Java array or convert them into Integer or Double objects • In Java 5, conversion from int to Integer and from double to Double is, in most cases, automatic (a feature known as autoboxing or autowrapping); the reverse conversion (called autounboxing) is also automatic. ArrayList<E> Autoboxing Example ArrayList<Integer> counts = new ArrayList<Integer>( ); counts.add(17); ... int count = counts.get(0); Autounboxing: count gets the value 17 Autoboxing: compiled as counts.add(new Integer(17)); ArrayList Pitfalls // Remove all occurences // of "like" from words: int i = 0; Caution: when you remove elements, a simple for loop doesn’t work: while (i < words.size()) for (int i = 0; i < words.size(); { i++) if ("like".equals(words.get(i)) { words.remove(i); if ("like".equals(words.get(i)) else words.remove(i); i++; } } Shifts all the elements after the i-th to the left and decrements the size “For Each” Loop • Introduced in Java 5 • Works both with standard arrays and ArrayLists • Convenient for traversing • Replaces iterators for collections (Chapter 19) “For Each” Loop: Example 1 int [ ] scores = { ... }; ... int sum = 0; for (int s : scores) { sum += s; Basically the same as: } ... for (int i = 0; i < scores.length; i++) { int s = scores[i]; sum += s; } “For Each” Loop: Example 2 ArrayList<String> words = new ArrayList<String>(); ... for (String str : words) { System.out.println(str); // process str } Basically the same as: for (int i = 0; i < words.size(); i++) { String str = words.get(i); System.out.println(str); } “For Each” Loop (cont’d) • You cannot add or remove elements within a “for each” loop. • You cannot change elements of primitive data types or references to objects within a “for each” loop. // Java1213.java // This program introduces the Java5.0 enhanced <for> loop // with an <int> array. public class Java1213 { public static void main(String args[]) { System.out.println("Java1213\n"); int list[] = {11,22,33,44,55,66,77,88,99}; for (int k = 0; k < 9; k++) // Old <for> loop syntax System.out.print(list[k] + " "); System.out.println("\n\n"); for (int item: list) // New <for> loop syntax System.out.print(item + " "); System.out.println("\n\n"); } } // Java1214.java // This program uses the Java 5.0 <for> loop with a <String> array. public class Java1214 { public static void main(String args[]) { System.out.println("Java1214\n"); String names[] = {"Tom","Sue","Joe","Jan","Bob","Lee","Ann","Meg"}; for (int k = 0; k < 8; k++) System.out.print(names[k] + " "); System.out.println("\n\n"); // Old <for> loop syntax for (String name: names) // New <for> loop syntax System.out.print(name + " "); System.out.println("\n\n"); } } // Java1215.java // This program demonstrates a very generalized <for..each> loop usage // with the <Object> class. public class Java1215 { public static void main(String args[]) { System.out.println("Java1215\n"); String names[] = {"Tom","Sue","Joe","Jan","Bob","Lee","Ann","Meg"}; for (int k = 0; k < 8; k++) System.out.print(names[k] + " "); System.out.println("\n\n"); for (Object obj: names) System.out.print(obj + " "); System.out.println("\n\n"); } } Enhancing the for Loop The enhanced for loop is called the for .. each loop. This loop structure is available in Java 5.0 The new loop structure does not replace the older for loop, because it is not possible to access specific array elements. int numbers[ ] = {1,2,3,4,5,6,7,8,9}; for (int number: numbers) System.out.print(number + " "); Inserting a Value into a Sorted Array • Given: an array, sorted in ascending order. The number of values stored in the array is smaller than array’s length: there are some unused elements at the end. • Task: insert a value while preserving the order. Inserting a Value (cont’d) 1. Find the right place to insert: 5 1 1 2 3 8 13 2. Shift elements to the right, starting from the5 last one: 1 1 2 3 8 13 3. Insert 1 1the 2value 3 in5its proper 8 13 place: Can be combined together in one loop: look for the place to insert while shifting. 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; } 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'; 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 } }; 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. 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: m.length m[3].length m.length m[0].length 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 ] } } “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: 1 + 2 + 3 + ... + n-1 = n (n - 1) / 2 AP Exam Alert The Arrays class is not part of the AP Java Subset and will not be tested. Students are expected to know how to use and implement array algorithms, such as traversing, element access, sorting and searching. In this chapter these array algorithms are used with the provided Arrays class methods. In a future Algorithm chapter you will learn how to implement these methods yourself. // Java1216.java // This program introduces the static <Arrays> class. // In this program the <toString> method is used to display the array elements. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1216 { public static void main (String args[]) { System.out.println("Java1216\n"); int list1[] = {11,22,33,44,55,66,77,88,99}; double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9}; char list3[] = {'A','B','C','D','E','F','G','H','I'}; String list4[] = {"AA","BB","CC","DD","EE","FF","GG","HH","II"}; System.out.println(Arrays.toString(list1)); System.out.println(Arrays.toString(list2)); System.out.println(Arrays.toString(list3)); System.out.println(Arrays.toString(list4)); System.out.println("\n\n"); } } Class Arrays Method toString Method toString displays the elements of an array object separated by commas and bounded by square brackets. [ ] int list[] = {11,22,33,44,55,66,77,88,99}; System.out.println(Arrays.toString(list)); // Java1217.java // This program demonstrates the <fill> method of the <Arrays> class. // The <fill> method assigns the same value to every array element. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1217 { public static void main (String args[]) { System.out.println("Java1217\n"); int list1[] = new int[10]; double list2[] = new double[10]; char list3[] = new char[10]; String list4[] = new String[10]; Arrays.fill(list1,123); Arrays.fill(list2,1.23); Arrays.fill(list3,'Q'); Arrays.fill(list4,"USA"); System.out.println(Arrays.toString(list1)); System.out.println(Arrays.toString(list2)); System.out.println(Arrays.toString(list3)); System.out.println(Arrays.toString(list4)); System.out.println("\n\n"); } } Class Arrays Method fill Method fill assigns the same value to every array element. int list1[] = new int[10]; double list2[] = new double[10]; char list3[] = new char[10]; String list4[] = new String[10]; Arrays.fill(list1,123); Arrays.fill(list2,1.23); Arrays.fill(list3,'Q'); Arrays.fill(list4,"USA"); // Java1218.java // This program demonstrates the <sort> method of the <Arrays> class. // Method <sort> arranges array elements in ascending order. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1218 { public static void main (String args[]) { System.out.println("Java1218\n"); int list1[] = {11,99,22,88,33,77,44,66,55}; double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9}; char list3[] = {'A','I','B','H','C','G','D','F','E'}; String list4[] = {"AA","II","BB","HH","CC","GG","DD","FF","EE"}; String list5[] = {"aardvark","bobcat","cougar","dog","ELEFANT","FOX","GORILLA","HARE"}; Arrays.sort(list1); Capital Letters have numeric Arrays.sort(list2); Arrays.sort(list3); code values from 65-90. Arrays.sort(list4); Arrays.sort(list5); System.out.println(Arrays.toString(list1)); System.out.println(Arrays.toString(list2)); System.out.println(Arrays.toString(list3)); System.out.println(Arrays.toString(list4)); System.out.println(Arrays.toString(list5)); System.out.println("\n\n"); } } Lowercase letters have numeric code values from 97-112. If lowercase letters are sorted together with capital letters, the capitals will come first because of the smaller code values. Class Arrays Method sort Method sort arranges the array elements in ascending order. String and character array elements are sorted in ascending order of the numerical code values. Incorrect processing may occur if string values are mixed upper-case and lower-case. int list1[] = {11,99,22,88,33,77,44,66,55}; double list2[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9}; char list3[] = {'A','I','B','H','C','G','D','F','E'}; Arrays.sort(list1); Arrays.sort(list2); Arrays.sort(list3); // Java1219.java // This program demonstrates the <binarySearch> method of the <Arrays> class. // Method <binarySearch> returns the index of a search element if it exists, // and returns a negative index value otherwise. import java.util.Arrays; // necessary to use the <Arrays> class public class Java1219 { public static void main (String args[]) { System.out.println("Java1219\n"); int list[] = {11,99,22,88,33,77,44,66,55}; System.out.println(Arrays.toString(list)); Arrays.sort(list); System.out.println(Arrays.toString(list)); System.out.println(); System.out.println("Index of 33 is " + Arrays.binarySearch(list,33)); System.out.println("Index of 11 is " + Arrays.binarySearch(list,11)); System.out.println("Index of 99 is " + Arrays.binarySearch(list,99)); System.out.println("Index of 10 is " + Arrays.binarySearch(list,10)); System.out.println("\n\n"); } } // Java1220.java // This program demonstrates that an array must be sorted before // the <binarySearch> method is called. // Erroneous indexes are returned if the list is import java.util.Arrays; not sorted!!! // necessary to use the <Arrays> class public class Java1220 { public static void main (String args[]) { System.out.println("Java1220\n"); int list[] = {11,99,22,88,33,77,44,66,55}; System.out.println(Arrays.toString(list)); System.out.println(); System.out.println("Index of 33 is " + Arrays.binarySearch(list,33)); System.out.println("Index of 11 is " + Arrays.binarySearch(list,11)); System.out.println("Index of 99 is " + Arrays.binarySearch(list,99)); System.out.println("Index of 10 is " + Arrays.binarySearch(list,10)); System.out.println("\n\n"); } } Class Arrays Method binarySearch Method binarySearch searches the elements of an array object for a specified value. The index of the array element is returned, if the element is found and a negative index is returned otherwise. Array elements must be sorted, otherwise the binarySearch method returns incorrect information. int list[] = {11,99,22,88,33,77,44,66,55}; System.out.println("Index of 33 is " + Arrays.binarySearch(list,33)); // Java1225.java // STATIC IMPORTS #1 // This program introduces static imports. // With Java 5.0 it is now possible to use class methods without the class identifier. // In this example the <System> class name is not necessary. import static java.lang.System.*; // necessary to eliminate the <System> identifier public class Java1225 { public static void main (String args[]) { System.out.println("Java1225\n"); ///// JAVA 1.4 ///// System.out.println("This demonstrates Java 1.4"); System.out.println(); System.out.println("The static class identifier <System> must be used.\n\n"); ///// JAVA 5.0 ///// out.println("This demonstrates Java 5.0"); out.println(); out.println("It is not necessary to use the <System> class identifier.\n\n"); } } // Java1226.java // STATIC IMPORTS #2 // This program introduces more static imports. // In this example the <Math> and <System class names are not necessary. import static java.lang.System.*; // necessary to eliminate the <System> identifier import static java.lang.Math.*; // necessary to eliminate the <Math> identifier public class Java1226 { public static void main (String args[]) { System.out.println("Java1226\n"); ///// JAVA 1.4 ///// System.out.println("Math class methods are a good example of working with static imports."); System.out.println(); System.out.println("The square root of 100 is " + Math.sqrt(100)); System.out.println("13 to the 4th power is " + Math.pow(13,4)); System.out.println("\n\n"); ///// JAVA 5.0 ///// out.println("Math class methods are a good example of working with static imports."); out.println(); out.println("The square root of 100 is " + sqrt(100)); out.println("13 to the 4th power is " + pow(13,4)); out.println("\n\n"); } } // Java1227.java // STATIC IMPORTS #3 // This program introduces more static imports. // In this example the <Arrays> and <System> class names are "sometimes" not necessary. import java.util.Arrays; // necessary to use the <Arrays> class import static java.lang.System.*; // necessary to eliminate the <System> identifier import static java.util.Arrays.*; // necessary to eliminate the <Arrays> identifier public class Java1227 { public static void main (String args[]) { System.out.println("Java1227\n"); int list[] = {12,56,34,91,65,27,45,70,85}; ///// JAVA 1.4 ///// System.out.println(Arrays.toString(list)); Arrays.sort(list); System.out.println(Arrays.toString(list)); System.out.println("\n\n"); ///// JAVA 5.0 ///// out.println(Arrays.toString(list)); sort(list); out.println(Arrays.toString(list)); out.println("\n\n"); } } // this is intentional; check next program // this is intentional; check next program // Java1228.java STATIC IMPORTS #4 // This program demonstrates a potential problem with static imports. // The <toString> method without the <Arrays> identifier confuses the Java compiler. // The <Object> class has a <toString> method, as do many other classes. // This program will not compile. import java.util.Arrays; // necessary to use the <Arrays> class import static java.lang.System.*; // necessary to eliminate the <System> identifier import static java.util.Arrays.*; // necessary to eliminate the <Arrays> identifier public class Java1228 { public static void main (String args[]) { System.out.println("Java1228\n"); int list[] = {12,56,34,91,65,27,45,70,85}; ///// JAVA 1.4 ///// System.out.println(Arrays.toString(list)); Arrays.sort(list); System.out.println(Arrays.toString(list)); System.out.println("\n\n"); ///// JAVA 5.0 ///// out.println(toString(list)); sort(list); out.println(toString(list)); out.println("\n\n"); } } Review: • Why are arrays useful? • What types of elements can an array have? • How do we refer to an array’s element in Java? • What happens if an index has an invalid value? • How do we refer to the length of an array? Review (cont’d): • Can we resize an array after it has been created? • Are arrays in Java treated as primitive data types or as objects? • What values do an array’s elements get when the array is created? • Are the array’s elements copied when an array is passed to a method? • Can a method return an array? Review (cont’d): • When is an ArrayList more convenient than an array? • Explain the difference between the capacity and size in an ArrayList? • What method returns the number of elements currently stored in an ArrayList? • What method is used to insert an element into an ArrayList? Review (cont’d): • What is autoboxing? • Can a double value be stored in an ArrayList<Double>? • Can a “for each” loop be used with ArrayLists? Standard arrays? • Describe an algorithm for inserting a value into a sorted array? • Can a class extend ArrayList<String>? Review (cont’d): • Name a few applications of twodimensional arrays. • If m is a 2-D array of ints, what is the type of m[0]? • How do we get the numbers of rows and cols in a 2-D array? // Java2011.java // This program tries to make a copy of the names1 <ArrayList> but does it improperly. // Instead of making a "deep copy" of the contents of names1, it only makes a "shallow copy" of the // memory address of names1. The result is aliasing. names1 and names2 are the exact same array // and when one <ArrayList> object is changed, the other is also changed. import java.util.ArrayList; public class Java2011 { public static void main(String args[]) { System.out.println(); System.out.println("Java2011.java\n"); ArrayList names1 = new ArrayList(); names1.add("Isolde"); names1.add("John"); names1.add("Greg"); names1.add("Maria"); names1.add("Heidi"); System.out.println("names1 contains " + names1); ArrayList names2 = names1; // This causes aliasing. System.out.println(); System.out.println("names2 contains " + names2); System.out.println(); names2.remove(0); // Removes the 1st name from the copied array System.out.println(); System.out.println("names1 contains " + names1); System.out.println(); System.out.println("names2 contains " + names2); System.out.println(); } } // Java2012.java // This program uses the <ArrayList> copy constructor to properly make a deep copy // of the contents of names1. Now when we remove the 1st name from names2 (the copy), // it does not have the aliasing side effect of altering names1 (the original). import java.util.ArrayList; public class Java2012 { public static void main(String args[]) { System.out.println(); System.out.println("Java2012.java\n"); ArrayList names1 = new ArrayList(); names1.add("Isolde"); names1.add("John"); names1.add("Greg"); names1.add("Maria"); names1.add("Heidi"); System.out.println("names1 contains " + names1); ArrayList names2 = new ArrayList(names1); System.out.println(); System.out.println("names2 contains " + names2); System.out.println(); names2.remove(0); System.out.println(); // Removes the 1st name from the copied array System.out.println("names1 contains " + names1); System.out.println(); System.out.println("names2 contains " + names2); System.out.println(); } } // Uses copy constructor // Java2013.java // This program shows another way to properly make a deep copy of an <ArrayList> object with // the <clone> method. import java.util.ArrayList; public class Java2013 { public static void main(String args[]) { System.out.println(); System.out.println("Java2013.java\n"); ArrayList names1 = new ArrayList(); names1.add("Isolde"); names1.add("John"); names1.add("Greg"); names1.add("Maria"); names1.add("Heidi"); System.out.println("names1 contains " + names1); ArrayList names2 = (ArrayList) names1.clone(); System.out.println(); System.out.println("names2 contains " + names2); System.out.println(); names2.remove(0); System.out.println(); // Removes the 1st name from the copied array System.out.println("names1 contains " + names1); System.out.println(); System.out.println("names2 contains " + names2); System.out.println(); } } Shallow Copy ArrayList names2 = names1; A shallow copy of an object only copies the memory address of the object and not the actual information stored. This results in aliasing and can cause side effects. names1 Isolde & names2 John Greg Maria Heidi Deep Copy ArrayList names2 = new ArrayList (names1); ArrayList names2 = (ArrayList) names1.clone(); A deep copy of an object creates an entirely new object and then copies the contents from one object to the other. This is the preferred way to copy objects and avoids aliasing. For ArrayList, this can be done with its copy constructor, or the clone method. When using the clone method, typecasting is necessary because the clone method returns a generic object. names1 Isolde John Greg Maria Heidi names2 Isolde John Greg Maria Heidi // Java2014.java // This program uses the <contains> method to determine if some object is an element // in an <ArrayList> object. It also uses the <indexOf> method to return the index of // a found element. import java.util.ArrayList; public class Java2014 { public static void main(String args[]) { System.out.println("Java2014.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add("Heidi"); System.out.println("names contains " + names); System.out.println(); System.out.println("Greg is a member of names: " + names.contains("Greg")); System.out.println("Suzy is a member of names: " + names.contains("Suzy")); System.out.println(); System.out.println("Greg is located at index: " + names.indexOf("Greg")); System.out.println("Suzy is located at index: " + names.indexOf("Suzy")); } } ArrayList Methods contains & indexOf System.out.println(names.contains("Greg")); System.out.println(names.indexOf("Greg")); The contains method returns true if the parameter value is an element of the names array object and false otherwise. The indexOf method returns the index of the parameter if the parameter is an element of the names object and -1 otherwise. Primitive Type Warning Java primitive types like int, double, char and boolean must be converted to object before they can be added to an ArrayList object. // Java2015.java // This program demonstrates that it is possible to store integers in an <ArrayList> object // with a "wrapper" class. It is easier to use a regular array to store primitive data elements. import java.util.ArrayList; public class Java2015 { public static void main(String args[]) { System.out.println(); System.out.println("Java2015.java\n"); ArrayList numbers = new ArrayList(); numbers.add(new Integer(12345)); numbers.add(new Integer(23451)); numbers.add(new Integer(34512)); numbers.add(new Integer(45123)); numbers.add(new Integer(51234)); for (int k = 0; k < numbers.size(); k++) System.out.println((Integer) numbers.get(k)); System.out.println(); } } // Java2016.java // This program demonstrates that integer stored into an <ArrayList> object cannot // be added with direct access, like static Java array elements. import java.util.ArrayList; import java.util.Random; public class Java2016 { public static void main(String args[]) { System.out.println("Java2016.java\n"); Random rand = new Random(12345); ArrayList numbers = new ArrayList(); for (int k = 1; k <= 48; k++) { int rndInt = (rand.nextInt(900) + 100); numbers.add(new Integer(rndInt)); } int sum = 0; for (int k = 0; k < numbers.size(); k++) sum += numbers.get(k); System.out.println("Sum: " + sum); } } // Java2017.java // This program demonstrates how to access the "int" value within an "integer" object. import java.util.ArrayList; import java.util.Random; public class Java2017 { public static void main(String args[]) { System.out.println("Java2017.java\n"); Random rand = new Random(12345); ArrayList numbers = new ArrayList(); for (int k = 1; k <= 48; k++) { int rndInt = (rand.nextInt(900) + 100); numbers.add(new Integer(rndInt)); } int sum = 0; for (int k = 0; k < numbers.size(); k++) { Integer temp = (Integer) numbers.get(k); sum += temp.intValue(); } System.out.println("Sum: " + sum); System.out.println(); } } // Java2018.java // This program takes an earlier program from the Algorithm chapter, implemented // with a <Person> array and converts it to an ArrayList implementation. import java.io.*; import java.util.*; public class Java2018 { public static void main(String args[]) throws IOException { System.out.println("Java2018.java\n"); List list = new List(); list.getList(); list.pause(); list.display(); list.pause(); list.bubbleSort(); list.display(); System.out.println(); } } class Person { public String name; public int age; public double gpa; Person(String n, int a,double g) { name = n; age = a; gpa = g; } } class List { private ArrayList students; public List() { students = new ArrayList(); } public void getList() throws IOException { System.out.println("\nRetrieving Students.dat\n"); FileReader inFile = new FileReader("Students.dat"); BufferedReader inStream = new BufferedReader(inFile); String s1,s2,s3; while( ((s1 = inStream.readLine()) != null) && ((s2 = inStream.readLine()) != null) && ((s3 = inStream.readLine()) != null) ) { String name = s1; int age = Integer.parseInt(s2); double gpa = Double.parseDouble(s3); students.add(new Person(name,age,gpa)); } inStream.close(); } public void display() { System.out.println("\nDISPLAYING LIST ELEMENTS"); for (int k = 0; k < students.size(); k++) { Person person = (Person) students.get(k); System.out.println(person.name + "\t\t" + person.age + "\t\t" + person.gpa); } } public void pause() { Scanner input = new Scanner(System.in); String dummy; System.out.print("\nPress <Enter> to continue ===>> "); dummy = input.nextLine(); } private void swap(int x, int y) { Person temp = (Person) students.get(x); students.set(x,students.get(y)); students.set(y,temp); } public void bubbleSort() { Person p, q; for (int s = 1; s < students.size(); s++) for (int t = 0; t < students.size()-s; t++) { p = (Person) students.get(t); q = (Person) students.get(t+1); if (p.gpa < q.gpa) swap(t,t+1); } } }