640 likes | 717 Views
Chapter 12 The ArrayList Data Structure. Go. Go. Section 1 - How to Instantiate an ArrayList Section 2 - The ArrayList Subset Section 3 - Declaring an ArrayList of Type List Section 4 - All About Wrapper Classes Section 5 - Writing Equals & CompareTo Methods. Go. Go. Go.
E N D
Chapter 12The ArrayList Data Structure Go Go Section 1 - How to Instantiate an ArrayList Section 2 - The ArrayList Subset Section 3 - Declaring an ArrayList of Type List Section 4 - All About Wrapper Classes Section 5 - Writing Equals & CompareTo Methods Go Go Go
Chapter 12 - Section 1What is an ArrayListand How Do You Instantiate One 2
12.1 What is an ArrayList? An ArrayList is a one-dimensional array. An ArrayList holds only objects, not primitive values like int, double, char or boolean. To place int and double values in an ArrayList, we will first “wrap them up” as Integer and Double objects. We will end up studying the wrapper classesInteger and Double as we works with ArrayLists. 3
12.1 The Disadvantage of Standard Arrays When you declare a standard array, you have to tell Java a fixed number of memory locations that you want the array to contain. During the run of a program, this cannot be changed unless you create a new standard array and copy all of the elements to it. This would be awkward to do and implement in every program that uses standard arrays. When you declare an ArrayList, you don’t haveto tell Java how much storage space you need. The ArrayList will be created for a beginning size of 10 and then it will automatically resize itself when it becomes full. 5
12.1 The Disadvantage of Standard Arrays You may have noticed when we worked with one-dimensional arrays that we didn’t remove data inside a listof values or add a new value to a list without overwriting one. We may have replaced a value but we didn’t insert a new one and shift the other values up the array, except in the TestInsertAndRemove program.You may remember that the code was tricky, but it becomes greatly simplified with ArrayLists. You’ll see that all we have to do is call methods and the work of shifting values is done for us behind the scene without writing any additional code. 6
12.1 Declaring & Instantiating an ArrayList ArrayList <Double>percentages = new ArrayList <Double> ( ); No square bracket [ ] notation is used with an ArrayList. Note the use of the templating angle brackets < and > that enclose the type of object to be placed in the ArrayList. Instead of using [] to identify the memory location to be accessed, methods are called to perform operations on the elements at a particular index or memory location. An ArrayList has indices like an array and the positions of the elements begin at index 0and go to index logical size - 1. 7
12.1 Instantiating Different Kinds of ArrayList Declaring and instantiating an ArrayList of other types: ArrayList <Integer> nums = new ArrayList <Integer> ( ); ArrayList <String> names = new ArrayList <String> ( ); ArrayList <Student> students = new ArrayList <Student> ( ); ArrayList <Shape> shapes = new ArrayList <Shape> ( ); Note the empty ( ) parentheses at the end of the constructor call.Don’t forget to include these. Here the default constructor of the ArrayList class is being called. 8
12.1 Instantiating the Size of an ArrayList You can declare and instantiate an ArrayList with an initial capacity of a certain sizeif you know approximately how many elements you will place in the ArrayList. The only real reason to do this is to keep the ArrayList from automatically resizing itself over and over again until all of the elements have been added to the ArrayList. However, this is not particularly inefficient for today’s computers unless you need to store many elements. For example, if you know you will have 1000 random integers in an ArrayList, you could use: ArrayList <Integer> nums = new ArrayList <Integer> (1000); 9
12.1 Default Values of ArrayList Objects Because ArrayLists have a logical size of zero when instantiated, we don’t ever assume that the lists have any kind of default values in them. If you try to get a value out of a newly constructed ArrayList then you will get this error message: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 All we know is that they have some initial size. The point is … don’t assume that the following two ArrayLists have default values of 0 stored in their memory locations … ArrayList <Integer> nums = new ArrayList <Integer> ( ); ArrayList <Double> percentages = new ArrayList <Double> ( ); and don’t assume that null values are stored in the memory locations of the following ArrayList: ArrayList <String> names = new ArrayList <String> ( ); 10
12.1 ArrayList Differences • As we have already mentioned, instead of using [] to manipulate elements, methods are called to perform operations. • An ArrayList tracks its logical size and physical size. Its logical size changes when elements are added to or removed from the ArrayList. Its physical size changes only if it is full and more elements need to be added. The ArrayList always knows these two values, but we only need to know one … the logical size. The size() method is used to get the number of elements an ArrayList. The size method is called a lot in loop headers. The logical size of an ArrayList is 0 when an is constructed and its logical size is automatically adjusted when an element is added or deleted. • An ArrayList does have indices and the positions of the elements range from index 0 to index logical size - 1. 11
12.1 Raw or Generic ArrayList? When you instantiate an ArrayList using angle brackets as you have just seen, we call it a generic ArrayList, because the programmer must specify the object type that the list will contain, as in … ArrayList <String> names = new ArrayList <String> ( ); Making a generic ArrayList with templating became available beginning with Java 1.5 and higher. Before that < > weren’t used. Prior to that, programmers could only make a raw ArrayList, where you could put all kinds of differen objects in the same ArrayList. So care had to be taken to make sure only one kind of object was placed in an ArrayList. You can still declare and instantiate a raw ArrayList, like the following, but most compilers will “complain” and at least give you a warning if you are using Java 1.5 or higher. (some people refer to Java 1.5 as Java 5). We never want to do the following: ArrayList names = new ArrayList ( ); 12
12.1 Advantages of ArrayList The following operations are much much easier for ArrayLists than for standard one-dimensional arrays: • traversing an ArrayList (accessing each element to print or perform an operation on it) • insertions anywhere in the ArrayList • removals anywhere in the ArrayList • searching an ArrayList An ArrayList tracks its own logical size and grows or shrinks automatically depending on the number of elements it has. 13
12.1 Importing the ArrayList Class To use the ArrayList class in a program, you must import it from the java.util package using: import java.util.ArrayList; 14
12.1 Using an ArrayList Parameter To use an ArrayList variable as a formal parameter in a method signature, declare the parameter the same way that you would declare an ArrayList variable when you are instantiating the ArrayList. Be sure and include in angle brackets the type of object that is contained in the ArrayList. Example: public void printList ( ArrayList < Integer> nums) { …….. } 15
12.2 The ArrayList Subset of Methods There are many methods in the ArrayList class if you look up its API on line. However, we only want to work with a few methods of the ArrayList class … those in particular that you are expected to know for the AP Exam. You might not receive full credit on a free response coding question if you try to use methods other than the ones specified by the College Board. So stick to the subset! The specified methods and what they do are listed on the next slide. 17
12.2 Adding Elements Using add(obj) The following code stores the first 100 multiples of 3 in nums in order: ArrayList <Integer> nums = new ArrayList <Integer> ( ); int value = 3; for (int i = 0; i < 100; i++) { nums.add(value); // adds at the end of the list value += 3; } Note: if nums was a standard array, we would use … nums [i] = value; in place of nums.add(value); 19
12.2 Getting Elements Using get(i) The following code prints the values stored in nums with 10 values per line with a field width of 5: for (int i = 0; i < nums.size(); i++) { if ( (i + 1) % 10 == 0 ) System.out.printf( “%5d%n”, nums.get(i) ); else System.out.printf( “%5d”, nums.get(i) ); } Note: if nums was a standard array, we would use … System.out.printf( “%5d”, nums[i]); 20
12.2 Getting Elements Using get(i) To obtain the first element in the ArrayList nums we would use … nums.get(0); To obtain the last element in an ArrayList we would use … nums.get(nums.size() - 1); Note that since there are num.size() elements in the ArrayList, then the index of the first element is 0 and the index of the last element is nums.size() - 1. 21
12.2 Removing Elements Using remove(i) The following code removes and prints all of the multiples of 6 from nums. int i = 0; while ( i < nums.size()) { if ( nums.get(i) % 6 == 0 ) { int x = nums.remove(i) ; System.out.printf( “%5d”, x ); // don’t increment i because elements are shifted down } else // if not evenly divisible by 6 increment i i++; } 22
12.2 Removing Elements Using remove(i) The following code removes and prints all of the multiples of 6 from nums in a field width of 5 using a for loop: for (int i = 0; i < nums.size() ; i++) { if ( nums.get(i) % 6 == 0 ) { int x = nums.remove(i) ; System.out.printf( “%5d”, x ); i--; // to cancel the effect of i++ in loop header } } 23
12.2 Removing Elements Using remove(i) To delete the first element in an ArrayList always use … nums.remove(0); // other values are shifted down To delete the last element in an ArrayList always use … nums. remove(nums.size() - 1); // no values shifted Again, since there are num.size() elements in the ArrayList, then the index of the first element is 0 and the index of the last element is nums.size() - 1. 24
12.2 Adding Elements Using add(i, obj) Assume an ArrayList initially contains 6, 9, 12. The following code adds the integer 3 at the first of the list. nums.add (0, 3);// add 3 at index 0 and shifts other values up The list now contains: 3 6 9 12 The following code adds the integer 15 at the end of the list no matter how many elements there are using the add(i, obj) method. nums.add (nums.size() , 15);// add 15 after the last element Since nums.size() is 4 before adding 15, then 15 is added at index 4. Obviously 3, 6, 9, & 12 are in indices 0, 1, 2, & 3. This is like adding at the “logical size”. The list now contains: 3 6 9 12 15 25
12.2 Replacing Elements Using set(i, obj) Assume nums contains: 3 6 9 12 15 The following code replaces the element at index 2 with the value 10 using the set(i, obj) method. It returns the replaced element and then we can print it out or do something with it. int x = nums.set (2, 10);// replace 9 at index 2 with 10 & returns 9. System.out.println(“The replaced value was ” + x); The list now contains: 3 6 10 12 15 Replacing the last value in the ArrayList … int x = nums.set (nums.size() - 1, 20); The list now contains: 3 6 10 12 20 26
12.3 The java.util.ArrayList Import The ArrayList class is part of the java.util package. So it is necessary to import this class by including: import java.util.ArrayList; The ArrayList class implementsthe List interface. That means that the ArrayList class must have all of the methods that are defined in the List interface. You will learn more about interfaces very soon, but we want to make you familiar with this fact now. The formal way to state this fact for the ArrayList class is: class java.util.ArrayList<E> implements java.util.List<E> The E in <E> simply stands for any kind of element, object, or class, like String, Integer, Double, Student, Employee, Shape etc. 28
12.3 Declaring Variables of type List Declaring and instantiating an ArrayList where the variable is of type List is the preferred way to go for many programmers. As you gain more experience programming you will understand why. Don’t worry about that too much for now, but realize that there is an alternate way to declare and instantiate an ArrayList using the List interface: List <Student> students = new ArrayList < Student > ( ); Compare this to the previous way: ArrayList <Student> students = new ArrayList < Student > ( ); 29
12.3 The java.util.ArrayList Import An interfacetells you the method signatures of the methods that classes that implement the interface must have. Here is what part of Java’s List interface looks like: public interface List { public intsize ( ); public booleanadd (E obj); public voidadd (int index, E obj); public Eget (int index); public Eset (int index, E obj); public Eremove (int index); ……. } You should recognize these methods. They are methods that are implemented in the ArrayList class. To use the interface, import the following: import java.util.List; 30
12.3 LinkedList Also Uses the List Interface A second class named theLinkedListclassalso implements the List interface. Since both of these classes have the same methods (but different code for them), we could choose to use the following declaration: List < Student > students = new LinkedList < Student > ( ); instead of … List <Student> students = new ArrayList < Student > ( ); This is one of the advantages of declaring variables of type List, because we don’t need to change any of the code in the program … only where students is declared and instantiated if we want to have a different kind of list. Some of the code in the LinkedList class is more efficient that the ArrayList class, because the LinkedList class is not based on a standard array but a different kind of list. You will learn about that if you take Advanced Computer Programming. 31
12.3 Declaring Variables of type List Also, if we declare the variable shapes to be of type List <Shape>, then if Shape is the parent of several classes like Circle, Rectangle, and Triangle, then we can hold all of those kinds of objects in the same ArrayList. This can be a real advantage. Now you are starting to learn about inheritance! List <Shape> shapes = new ArrayList <Shape> ( ); We will work with the Shape interface very soon. 32
12.3 Importing the List Interface To be able to declarean ArrayList variable of type Listin a program, you must import the List interface from the java.util package using: import java.util.List; 33
12.3 Using a List Parameter To use a List variable as a formal parameter in a method signature of a program,declare the parameter the same way that you would declare a List variable. Example: public void printList ( List < Integer> nums) { …….. } 34
12.4 Wrapper Classes The Integer and Double classes are called wrapper classes, because they are used to “wrap up” primitive int and double values as objects so they can be put in an ArrayList or other kind of data structure that requires object data types. We used the Integer and Double classes earlier this year when we used … Integer.parseInt()and Double.parseDouble() to get the values from JTextFields or InputDialog boxes. Now let’s look a little closer at the Integer and Double classes see how to wrap up an int or double as an object. 36
12.4 Wrapping & Unwrapping ints You don’t need to know the parseInt() method for the AP Exam, but you do need to know how to use the following methods of the Integer class: The constructor that has one parameter that is an int. If you want to wrap upan int, like 345, as an Integer object, then you would use the constructor to wrap it up: Integer intObj = new Integer (345); You have now wrapped up the int 345and made it an Integer object and the variable intObj refers to that object! To unwrap or get the Integer object out of intObj and store it in the int variable x, then you can call the intValue() method … int x = intObj.intValue(); 37
12.4 Wrapping & Adding Integers For the ArrayList … ArrayList <Integer> nums = new ArrayList <Integer> ( ); if we want to place the primitive values 5, 10, and 15 in nums, then formally, we should wrap them up and add them as follows: Integer intObj1 = new Integer(5); nums.add(intObj1); // adds to the end of the list Integer intObj2 = new Integer(10); nums.add(intObj2); // adds to the end of the list You can also combine the lines by using … nums.add(new Integer(15));// adds to the end of the list 38
12.4 Autoboxing Integers Prior to Java 1.5, with a raw ArrayList, you always had to wrap upint values. However, with the advent of Java 1.5 autoboxing became available. Here is the same code using autoboxing. ArrayList <Integer> nums = new ArrayList <Integer> ( ); nums.add(5); // autoboxing 5 (automatically wrapping it up) nums.add(10); // autoboxing 10 (automatically wrapping it up) nums.add(15); // autoboxing 15 (automatically wrapping it up) Even though, the College Board allows you to write code that autoboxes values, they still want you to know how to wrap up int values and you may see wrapper code on the multiple choice test that doesn’t include autoboxing. 39
12.4 Unboxing Integers Prior to Java 1.5 with a raw ArrayList, you had to unwrap int values before using them. However, with the advent of Java 1.5 unboxing became available. Here is the code with unboxing: int x = nums.get(0); // the returned Integer is automatically unboxed int y = nums.get(1); // the returned Integer is automatically unboxed int z = nums.get(2); // the returned Integer is automatically unboxed Here intValue() is called automatically by Java to unwrap the Integer object returned by get(i) so it can be stored in x, y, or z. You don’t have to call intValue() to unwrap because of unboxing! However, the College Board still wants you to know how to unwrap Integer objects. 40
12.4 Wrapping & Unwrapping doubles You don’t need to know the parseDouble() method for the AP Exam, but you do need to know how to use the following methods of the Double class: The constructor that has one parameter that is a double. If you want to wrap upa double, like 12.3, as a Double object, then you would use the constructor to wrap it up: Double floatObj = new Double(12.3); You have now wrapped up the double 12.3and made it a Double object and the variable floatObj refers to that object! To unwrapthe Double object floatObj and get the double value 12.3 out of it and store it in the double variable d, then you have to call the doubleValue() method … double d = floatObj.doubleValue(); 41
12.4 Wrapping & Adding Doubles For the ArrayList … ArrayList <Double> floats = new ArrayList <Double> ( ); if we want to place the values 5.5, 6.6, and 7.7 in floats, in that order, we would wrap them up and add them as follows: Double floatObj1 = new Double (5.5); floats.add(floatObj1); // adds to the end of the list Double floatObj2 = new Double (6.6); floats.add(floatObj2 ); // adds to the end of the list You can also combine the lines by using … floats.add(new Double(7.7));// adds to the end of the list 42
12.4 Autoboxing Doubles Prior to Java 1.5, with a raw ArrayList, you had to wrap up double values. However, with the advent of Java 1.5 autoboxing became available. Here is the same code with autoboxing: ArrayList <Double> floats = new ArrayList < Double > ( ); floats.add(5.5); // autoboxing 5.5 (automatically wrapping it up) floats.add(6.6); // autoboxing 6.6 (automatically wrapping it up) floats.add(7.7); // autoboxing 7.7 (automatically wrapping it up) However, the College Board still wants you to know how to wrap up double values. 43
12.4 Unboxing Doubles Prior to Java 1.5 with a raw ArrayList, you had to unwrap double values before using them. However, with the advent of Java 1.5 unboxing became available. Here is the code with unboxing: double b = floats.get(0); // the returned Double is automatically unboxed double c = floats.get(1); // the returned Double is automatically unboxed double d = floats.get(2); // the returned Double is automatically unboxed Here doubleValue() is called automatically by Java to unwrap the Double object returned by get(i) so it can be stored in b, c, or d. You don’t have to call doubleValue() to unwrap because of unboxing! However, the College Board still wants you to know how to unwrap Integer objects. 44
Chapter 12 - Section 5Writing an Equals Method for a Model Class 45
12.5 The Use of the Equals Methods You may have seen the use of the equals() method when comparing String values previously instead of using compareTo(“?”) == 0. Since String values are objects, it is necessary to use one of these two to check the contents of a String objectto see if it is equal to the contents of another String object or a literal String. The College Board does not formally recognize the use of the equals method. However, checking for equality is necessary when searching for a particular object that is in a list, and it is actually simpler to use the equals method when testing for equality … especially one that is in a one or two-dimensional array or in an ArrayList. 46
12.5 The Use of the Equals Methods Either of the following code segments can be used to test for String equality, because the String class has both an equals method and it has a compareTo method. String pet1 = “dog”; String pet2 = “cat”; if ( pet1.compareTo(pet2) == 0 ) …. If ( pet1.equals(pet2) ) …. You can see that the second one is easier to write. 47
12.5 The Student Class Equals Methods A Student object as we currently know it has three instance variables, a String name, an int id number and an integer array of test values. Before we write an equals method for a class like Student, we need to decide what we want to base our equality of two students on. You will write an equals method for the Student class where equality for two students is based on their names and id numbers.It won’t matter what the test scores for the two Student objects is. This may not make sense to you because obviously you could have two students with the same name. However, this will suffice for demonstration purposes, but it underscores the need for careful consideration when choosing the basis for equality. 48
12.5 The Person Class Equals Methods So you will know how to write the Student class equals and compareTo methods, let’s look first at an example of an equals method for the Person class. Equality for two Person objects will be based on their names and their addresses. If you write an equals method for any class, it must have this exact method signature: publicboolean equals (Object other) This is because it must override the equals method of the Object class. 49
12.5 The Person Class Equals Method Code // This method is used checking two Person objects for equality. publicboolean equals (Object other) { // Check to see if the receiver object is the exact same object as the parameter object. // If it is then return true. The contents would be the same in this case. if (this == other) returntrue; // If the parameter object is not of the same type as the receiver object, // then throw an exception. if (! (other instanceof Person) ) // if other is NOT an instance of the Person class thrownew IllegalArgumentException ( "The object you are passing is NOT a Person!"); // cast other to a Person because the parameter is of generic type Object Person p = (Person) other; // call the String equals method to test the names and addresses for equality if (this.name.equals(p.name) && this.address.equals(p.address)) returntrue; returnfalse; } 50