Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 12 The ArrayList Data Structure Section 1 - How to Instantiate an ArrayList Section 2 - The ArrayList Subset Section 3 - Declaring an ArrayList.

Similar presentations


Presentation on theme: "Chapter 12 The ArrayList Data Structure Section 1 - How to Instantiate an ArrayList Section 2 - The ArrayList Subset Section 3 - Declaring an ArrayList."— Presentation transcript:

1

2 Chapter 12 The ArrayList Data Structure 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

3 Chapter 12 - Section 1 What is an ArrayList and How Do You Instantiate One 2

4 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 classes Integer and Double as we works with ArrayLists. 3

5 12.1 The ArrayList Subset of Methods ArrayList methodWhat the Operation Does int size ( )returns the logical size of the list boolean add (E obj)appends the object obj to the end of the list and returns true if successful (the fact that it returns true may be helpful sometimes) void add (int i, E obj)inserts the object obj at position i where the position i fulfills the expression 0 ≤ i ≤ size. If i is out of bounds in the range of i size(), then Java throws an IndexOutOfBoundsException. Once obj is inserted, then the elements at position i and higher are moved to the right so that 1 is added to their indices and then the logical size is adjusted. Note: if there are 3 elements in the list at indices 0, 1, and 2, then obj can be added as the new last element at index 3 without an out of bounds error E get (int i)returns the element at position i in the list E set (int i, E obj)replaces the element at position i with obj and returns the element formerly at the specified position E remove (int i)removes the element from position i in the list and then moves all elements at position i + 1 and higher to the left … subtracting 1 from their indices and then adjusting the logical size. The element formerly at the specified position is returned 4

6 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 have to 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

7 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 list of 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

8 12.1 Declaring & Instantiating an ArrayList ArrayList percentages = new ArrayList ( ); No square bracket [ ] notation is used with an ArrayList. Note the use of the templating angle brackets 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 0 and go to index logical size - 1. 7

9 12.1 Instantiating Different Kinds of ArrayList Declaring and instantiating an ArrayList of other types: ArrayList nums = new ArrayList ( ); ArrayList names = new ArrayList ( ); ArrayList students = new ArrayList ( ); ArrayList shapes = new ArrayList ( ); 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

10 12.1 Instantiating the Size of an ArrayList You can declare and instantiate an ArrayList with an initial capacity of a certain size if 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 nums = new ArrayList (1000); 9

11 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 nums = new ArrayList ( ); ArrayList percentages = new ArrayList ( ); and don’t assume that null values are stored in the memory locations of the following ArrayList: ArrayList names = new ArrayList ( ); 10

12 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

13 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 names = new ArrayList ( ); 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

14 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

15 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

16 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 nums) { …….. } 15

17 Chapter 12 - Section 2 The ArrayList Subset 16

18 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

19 12.2 The ArrayList Subset of Methods ArrayList methodWhat the Operation Does int size ( )returns the logical size of the list boolean add (E obj)appends the object obj to the end of the list and returns true if successful (the fact that it returns true may be helpful sometimes) void add (int i, E obj)inserts the object obj at position i where the position i fulfills the expression 0 ≤ i ≤ size. If i is out of bounds in the range of i size(), then Java throws an IndexOutOfBoundsException. Once obj is inserted, then the elements at position i and higher are moved to the right so that 1 is added to their indices and then the logical size is adjusted. Note: if there are 3 elements in the list at indices 0, 1, and 2, then obj can be added as the new last element at index 3 without an out of bounds error E get (int i)returns the element at position i in the list E set (int i, E obj)replaces the element at position i with obj and returns the element formerly at the specified position E remove (int i)removes the element from position i in the list and then moves all elements at position i + 1 and higher to the left … subtracting 1 from their indices and then adjusting the logical size. The element formerly at the specified position is returned 18

20 12.2 Adding Elements Using add(obj) The following code stores the first 100 multiples of 3 in nums in order: ArrayList nums = new ArrayList ( ); 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 Chapter 12 - Section 3 Declaring ArrayLists of Type List 27

29 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 implements the 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 implements java.util.List The E in simply stands for any kind of element, object, or class, like String, Integer, Double, Student, Employee, Shape etc. 28

30 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 students = new ArrayList ( ); Compare this to the previous way: ArrayList students = new ArrayList ( ); 29

31 12.3 The java.util.ArrayList Import An interface tells 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 int size ( ); public boolean add (E obj); public void add (int index, E obj); public E get (int index); public E set (int index, E obj); public E remove (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

32 12.3 LinkedList Also Uses the List Interface A second class named the LinkedList class also 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 students = new LinkedList ( ); instead of … List students = new ArrayList ( ); 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

33 12.3 Declaring Variables of type List Also, if we declare the variable shapes to be of type List, 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 shapes = new ArrayList ( ); We will work with the Shape interface very soon. 32

34 12.3 Importing the List Interface To be able to declare an ArrayList variable of type List in a program, you must import the List interface from the java.util package using: import java.util.List; 33

35 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 nums) { …….. } 34

36 Chapter 12 - Section 4 All About Wrapper Classes 35

37 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

38 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 up an 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 345 and 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

39 12.4 Wrapping & Adding Integers For the ArrayList … ArrayList nums = new ArrayList ( ); 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

40 12.4 Autoboxing Integers Prior to Java 1.5, with a raw ArrayList, you always had to wrap up int values. However, with the advent of Java 1.5 autoboxing became available. Here is the same code using autoboxing. ArrayList nums = new ArrayList ( ); 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

41 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

42 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 up a 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.3 and made it a Double object and the variable floatObj refers to that object! To unwrap the 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

43 12.4 Wrapping & Adding Doubles For the ArrayList … ArrayList floats = new ArrayList ( ); 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

44 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 floats = new ArrayList ( ); 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

45 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

46 Chapter 12 - Section 5 Writing an Equals Method for a Model Class 45

47 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 object to 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

48 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

49 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

50 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: public boolean equals (Object other) This is because it must override the equals method of the Object class. 49

51 12.5 The Person Class Equals Method Code // This method is used checking two Person objects for equality. public boolean 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) return true; // 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 throw new 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)) return true; return false; } 50

52 12.5 Two Ways of Checking Equality We use == to check for the equality of primitive data types like int, double, and boolean, but with object data types we must use an equals method, like with String data types. Remember, when we first discussed aliasing, we said that two reference variables can point to same object. If we were to use == to compare two reference variables, then we would be checking to see if the variables point to the same object. But as we learned with reference variables that point at String objects, if we want to check the values ( the contents) of two distinct objects for equality, we must use the equals method. 51

53 12.5 Checking Alias Variables Student s1, s2; s1 = new Student (“Bill”, 93, 84, 79); s2 = s1; // create an alias of s1 if (s1 == s2) // perform operation 1 else // perform operation 2 Bill 93 84 79 Which operation will be executed? 52 s1 s2

54 12.5 Checking Alias Variables Student s1, s2; s1 = new Student (“Bill”, 93, 84, 79); s2 = s1; // create an alias of s1 if (s1 == s2) // perform operation 1 else // perform operation 2 s1 Bill 93 84 79 operation 1 will be executed, because s1 == s2 is true since s1 and s2 point at the same object. 53 Just remember that if (s1 == s2) asks “Does s1 point at the same object that s2 points at?” s2

55 Bill 93 84 79 Student s1, s2; s1 = new Student (“Bill”, 93, 84, 79); s2 = new Student (“Mary”, 95, 89, 92); if (s1 == s2) // perform operation 1 else // perform operation 2 Mary 95 89 92 54 12.5 Checking Non-Alias Variables Which operation will be executed? s1 s2

56 Bill 93 84 79 Student s1, s2; s1 = new Student (“Bill”, 93, 84, 79); s2 = new Student (“Mary”, 95, 89, 92); if (s1 == s2) // perform operation 1 else // perform operation 2 Mary 95 89 92 55 12.5 Checking Non-Alias Variables operation2 will be executed, because (s1 == s2) is false since s1 and s2 point at different objects s1 s2

57 12.5 The Object Class Equals Method The equals method is defined in the Object class, which is at the top of all classes in the Java heirarchy. The Object class equals method uses the == operator by default in its code … and does NOT compare content but rather compares memory locations. If the two object variables reference the same memory location, then == returns true and the Object class method returns true. It wouldn’t be possible to check for contents since that equals method has no idea of what kind of objects are being compared. 56

58 12.5 Overriding the Object Class Equals Method So if we design a model class that defines a particular kind of object, then we should provide an equals method so objects of that class can be checked for equality not for references. If we don’t provide an equals method, and code is written that accidentally call equals, then the equals() method of the Object class is called in its place and content is NOT checked but rather the references. When we write our own equals method for a class, we are overriding the equals method of the Object class. This is a good thing! 57

59 12.5 Code Example of == and Equals 58 Consider the following code segment, which reads a string from the keyboard, uses both methods to compare this string to a literal string value, and then outputs the results: String str = reader.nextLine(); System.out.println (str == “Java”); Displays false no matter what string is entered because “Java” is a literal string and a String object for it is created. The variable str gets a totally different String object and the value from the keyboard is placed in it. System.out.println (str.equals ("Java")); Displays true if the string entered was "Java", and false otherwise

60 12.5 Additional Explanation of == Operator So, the operator == compares the references to objects, not the contents of objects. Thus, if two reference variables do not point to the same object in memory, == returns false. Because the two strings in our previous example are not the same object in memory, == returns false. 59

61 12.5 Summarizing Object Identity To summarize, == tests for object identity and different objects in memory have different identities. whereas equals tests for content equality of two objects. Now you are better prepared to understand the code of the equals method of the Person class, and you should design the equals method of the Student class in the same way. Let’s review the Person class equals method again. 60

62 12.5 The Person Class Equals Method Code // This method is used checking two Person objects for equality. public boolean 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) return true; // 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 throw new 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)) return true; return false; } 61

63 12.5 Checking a List of Objects for a Target So let’s say you have a list of Person objects stored in an ArrayList and you are looking for a particular (target) Person. You can use a loop inside a method to go through the list (traverse) and compare each Person in the list to the target using the equals method of the Person class. Here is the framework of such a loop using the List persons that is passed to a method: List persons = new ArrayList (); for (int i = 0; i < persons.size(); i++) { if ( persons.get(i).equals(target) ) ???? 62

64 12.5 Using == with Window Objects The operator == can also be used with other objects, such as buttons and menu items. In these cases, the operator still tests for object identity (a reference to the same object in memory). With window objects, the use of == is appropriate because most of the time we want to compare references (not the contents). We did this when using the code: if (e.getSource() == clearBtn) For other objects, however, the use of == should be avoided. 63


Download ppt "Chapter 12 The ArrayList Data Structure Section 1 - How to Instantiate an ArrayList Section 2 - The ArrayList Subset Section 3 - Declaring an ArrayList."

Similar presentations


Ads by Google