Presentation is loading. Please wait.

Presentation is loading. Please wait.

First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.

Similar presentations


Presentation on theme: "First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types."— Presentation transcript:

1

2 First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.

3 Data Structure Starting Point Any data type that can store more than one value is a data structure.

4 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.

5 First Record Definition A record is a data structure with one, or more, elements, called fields, of the same or different data types.

6 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.

7 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.

8 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.

9 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.

10 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.691.74 0.0 An array of doubles

11 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. c[0]c[1]c[2]c[3] 1.39 1.691.74 0.0 c is array’s name

12 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

13 Defining Static Arrays int list[ ]; // declares the array list identifier list = new int[10]; // allocates memory for 10 integers char names[ ]; // declares the names array identifier names = new char[25]; // allocates memory for 25 characters double grades[ ]; // declares the grades array identifier grades = new double[50]; // allocates memory for 50 doubles

14 Defining Static Arrays Preferred Method int list[ ] = new int[10]; char names[ ] = new char[25]; double grades[ ] = new double[50];

15 // 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(); } 0123456789 0000000000

16 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.

17 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.

18 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()) ]

19 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.

20 // 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(); } 0123456789 0000000000

21 // Java1203.java // This program demonstrates how to initialize array elements. // The 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(); } 012345678 112233445566778899

22 // 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(); } list1 01234 ????? list2 0123 char

23 // 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(); } 0123456789

24 // 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]); System.out.println(); } list1 01234 null list2 01234 AAABBBCCCDDDEEE

25 // 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(); } 012345678910111213141516171819 851680241928455284575802701889717142890206312584687803432775

26 // 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(); } 0123 JoeTomSueMeg

27 // 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(); } 0123456789 AABBCCDDEEFFGGHHIIJJ

28 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. int sum = 0; sum += score0; sum += score1; … sum += score999; No arrays: int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; With arrays: 1000 times!

29 Why Arrays? (cont’d) Arrays give direct access to any element — no need to scan the array. if (k == 0) display (score0); else if (k == 1) display (score1); else … // etc. display (scores[k]); 1000 times! No arrays: With arrays:

30 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;

31 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!

32 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: scores = new int [10] ; words = new String [10000]; length 10, all values set to 0 length 10000, all values set to null

33 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" };

34 String [ ] words;... words = new String [ console.readInt() ]; private double[ ] gasPrices; … gasPrices = new double[ ] { 3.05, 3.17, 3.59 }; Initialization (cont’d) Otherwise, initialization can be postponed until later. For example: Not yet initialized

35 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.

36 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.

37 Initializing Elements (cont’d) Example: Color[ ] pens;... pens = new Color [ 3 ];... pens [0] = Color.BLUE; pens [1] = new Color (15, 255, 255); pens [2] = g.getColor(); Now all three elements are initialized Array is created; all three elements are set to null Array not created yet

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; }

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[ ].

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) };

41 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. AP Exam Alert

42 java.util.ArrayList 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 elements currently in the list) "Cat""Hat""Bat" capacity size...

43 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 words = new ArrayList (); ArrayList nums = new ArrayList ();

44 ArrayList Constructors ArrayList ( ) ArrayList (int capacity) Creates an empty ArrayList of default capacity (ten) Java docs use the letter E as the type parameter for elements in generic collections Creates an empty ArrayList of the specified capacity

45 // Java2004.java // This program introduces the class with the 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(); }

46 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!

47 ArrayList Methods (a Subset) int size() boolean isEmpty () boolean add (E obj) void add (int i, E obj) E set(int i, E obj) E get(int i) E remove(int i) boolean contains(E obj) int indexOf(E obj) use equals to compare objects i must be from 0 to size() - 1 inserts obj as the i-th value; i must be from 0 to size() returns true

48 ArrayList Example ArrayList names = new ArrayList ( ); names.add("Ben"); names.add("Cat"); names.add(0, "Amy"); System.out.println(names); [Amy, Ben, Cat] Output ArrayList’s toString method returns a string of all the elements, separated by commas, within [ ].

49 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.

50 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]

51 // Java2005.java // This program uses the 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(); }

52 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.

53 // Java2006.java // This program shows how to access specified elements in an object // with the 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)); }

54 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.

55 // Java2007.java // This program demonstrates the method of the 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); }

56 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.

57 // Java2008.java // This program demonstrates the method of the 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(); }

58 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.

59 // Java2009.java // This program demonstrates how to use the method of the 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); }

60 ArrayList Method add (2 nd 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.

61 // Java2010.java // This program demonstrates how to use the method to remove all the // array elements and the 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(); }

62 ArrayList 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) )

63 ArrayList 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.

64 ArrayList Autoboxing Example ArrayList counts = new ArrayList ( ); counts.add(17);... int count = counts.get(0); Autoboxing: compiled as counts.add(new Integer(17)); Autounboxing: count gets the value 17

65 ArrayList Pitfalls // Remove all occurences // of "like" from words: int i = 0; while (i < words.size()) { if ("like".equals(words.get(i)) words.remove(i); else i++; } for (int i = 0; i < words.size(); i++) { if ("like".equals(words.get(i)) words.remove(i); } Shifts all the elements after the i-th to the left and decrements the size Caution: when you remove elements, a simple for loop doesn’t work:

66

67 “For Each” Loop Introduced in Java 5 Works both with standard arrays and ArrayLists Convenient for traversing Replaces iterators for collections (Chapter 19)

68 “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; }

69 “For Each” Loop: Example 2 ArrayList words = new ArrayList ();... 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); }

70 “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.

71 // Java1213.java // This program introduces the Java5.0 enhanced loop // with an 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 loop syntax System.out.print(list[k] + " "); System.out.println("\n\n"); for (int item: list) // New loop syntax System.out.print(item + " "); System.out.println("\n\n"); }

72 // Java1214.java // This program uses the Java 5.0 loop with a 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] + " ");// Old loop syntax System.out.println("\n\n"); for (String name: names) // New loop syntax System.out.print(name + " "); System.out.println("\n\n"); }

73 // Java1215.java // This program demonstrates a very generalized loop usage // with the 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"); }

74 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 + " ");

75 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.

76 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: 1123813 5 11238 5 11235 8 Can be combined together in one loop: look for the place to insert while shifting.

77 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; }

78 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';

79 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 } };

80 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.

81 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].lengthm[0].length m.length

82 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 ] }

83 “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

84

85 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. AP Exam Alert

86 // Java1216.java // This program introduces the static class. // In this program the method is used to display the array elements. import java.util.Arrays;// necessary to use the 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"); }

87 Method toString displays the elements of an array object separated by commas and bounded by square brackets. [ ] Class Arrays Method toString int list[] = {11,22,33,44,55,66,77,88,99}; System.out.println(Arrays.toString(list));

88 // Java1217.java // This program demonstrates the method of the class. // The method assigns the same value to every array element. import java.util.Arrays;// necessary to use the 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"); }

89 Method fill assigns the same value to every array element. Class Arrays Method fill 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");

90 // Java1218.java // This program demonstrates the method of the class. // Method arranges array elements in ascending order. import java.util.Arrays;// necessary to use the 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); Arrays.sort(list2); Arrays.sort(list3); 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"); } Capital Letters have numeric code values from 65-90. 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.

91 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. Class Arrays Method sort 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);

92 // Java1219.java // This program demonstrates the method of the class. // Method 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 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"); }

93 // Java1220.java // This program demonstrates that an array must be sorted before // the method is called. // Erroneous indexes are returned if the list is not sorted!!! import java.util.Arrays;// necessary to use the 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"); }

94 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. Class Arrays Method binarySearch int list[] = {11,99,22,88,33,77,44,66,55}; System.out.println("Index of 33 is " + Arrays.binarySearch(list,33));

95

96 // 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 class name is not necessary. import static java.lang.System.*; // necessary to eliminate the 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 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 class identifier.\n\n"); }

97 // Java1226.java // STATIC IMPORTS #2 // This program introduces more static imports. // In this example the and <System class names are not necessary. import static java.lang.System.*; // necessary to eliminate the identifier import static java.lang.Math.*; // necessary to eliminate the 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"); }

98 // Java1227.java // STATIC IMPORTS #3 // This program introduces more static imports. // In this example the and class names are "sometimes" not necessary. import java.util.Arrays;// necessary to use the class import static java.lang.System.*;// necessary to eliminate the identifier import static java.util.Arrays.*; // necessary to eliminate the 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));// this is intentional; check next program sort(list); out.println(Arrays.toString(list));// this is intentional; check next program out.println("\n\n"); }

99 // Java1228.java STATIC IMPORTS #4 // This program demonstrates a potential problem with static imports. // The method without the identifier confuses the Java compiler. // The class has a method, as do many other classes. // This program will not compile. import java.util.Arrays;// necessary to use the class import static java.lang.System.*;// necessary to eliminate the identifier import static java.util.Arrays.*;// necessary to eliminate the 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"); }

100 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?

101 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?

102 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?

103 Review (cont’d): What is autoboxing? Can a double value be stored in an ArrayList ? 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 ?

104 Review (cont’d): Name a few applications of two- dimensional 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?

105

106 // Java2011.java // This program tries to make a copy of the names1 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 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(); }

107 // Java2012.java // This program uses the 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); // Uses copy constructor 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(); }

108 // Java2013.java // This program shows another way to properly make a deep copy of an object with // the 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); // 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(); }

109 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 & names2 IsoldeJohnGregMariaHeidi

110 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 IsoldeJohnGregMariaHeidi names2 IsoldeJohnGregMariaHeidi Deep Copy

111 // Java2014.java // This program uses the method to determine if some object is an element // in an object. It also uses the 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")); }

112 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.

113 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.

114 // Java2015.java // This program demonstrates that it is possible to store integers in an 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(); }

115 // Java2016.java // This program demonstrates that integer stored into an 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); }

116 // 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(); }

117 // Java2018.java // This program takes an earlier program from the Algorithm chapter, implemented // with a 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; } }

118 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(); }

119 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 to continue ===>> "); dummy = input.nextLine(); }

120 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); }

121


Download ppt "First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types."

Similar presentations


Ads by Google