Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction Chapter 12 introduced the array data structure. Historically, the array was the first data structure used by programming languages. With.

Similar presentations


Presentation on theme: "Introduction Chapter 12 introduced the array data structure. Historically, the array was the first data structure used by programming languages. With."— Presentation transcript:

1

2 Introduction Chapter 12 introduced the array data structure. Historically, the array was the first data structure used by programming languages. With arrays you learned to store multiple values in a single variable. You also learned that access to any individual array element is possible with a special index operator [ ].

3 Static Array Limitations The actual introduction of the ArrayList class needs to wait for a brief review of the Java static array. // Java2001.java // This program fills a static integer array with 10 random numbers. import java.util.Random; import java.io.*; public class Java2001 { public static void main (String args[]) { System.out.println("\nJava2001.java\n"); int list[] = new int[10]; Random random = new Random(12345); for (int k = 0; k < 10; k++) list[k] = random.nextInt(900) + 100; for (int k = 0; k < 10; k++) System.out.print(list[k] + " "); System.out.println("\n\n"); }

4 // Java2002.java // This program enters the array size during program execution. import java.util.*; public class Java2002 { public static void main (String args[]) { System.out.println("\nJava2002.java\n"); Scanner input = new Scanner(System.in); System.out.print("Enter array size ===>> "); int size = input.nextInt(); System.out.println(); int list[] = new int[size]; Random random = new Random(12345); for (int k = 0; k < size; k++) list[k] = random.nextInt(900) + 100; for (int k = 0; k < size; k++) System.out.print(list[k] + " "); System.out.println("\n\n"); }

5

6 // Java2003.java This program attempts to resize the list array. // It does resize during program execution, but it destroys the existing array. import java.util.*; public class Java2003 { public static void main (String args[]) { System.out.println("\nJava2003.java\n"); Scanner input = new Scanner(System.in); System.out.print("Enter array size ===>> "); int size = input.nextInt(); System.out.println(); int list[] = new int[size]; Random random = new Random(12345); for (int k = 0; k < size; k++) list[k] = random.nextInt(900) + 100; for (int k = 0; k < size; k++) System.out.print(list[k] + " "); System.out.println("\n\n"); System.out.print("Enter array size ===>> "); size = input.nextInt(); System.out.println(); list = new int[size]; for (int k = 11; k < size; k++) list[k] = random.nextInt(900) + 100; for (int k = 0; k < size; k++) System.out.print(list[k] + " "); System.out.println("\n\n"); }

7

8 Static ArrayLists and Resizing Java static arrays cannot be altered after they are constructed. It is possible to use the same array identifier to construct a different object with a different size. Any of the values stored in the original object will be lost.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

27 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

28 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

29 // 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")); }

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

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

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

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

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

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

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

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

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

39

40

41 // Java2019.java // This demonstrates how class objects are printed. public class Java2019 { public static void main (String args[]) { System.out.println("\nJava2019.java\n"); String stringVar = "Tango"; System.out.println(stringVar); System.out.println(); System.out.println("Literal String"); System.out.println(); }

42 // Java2020.java // This demonstrates how,, and // variables are printed. public class Java2020 { public static void main (String args[]) { System.out.println("\nJava2020.java\n"); int intVar = 100; double dblVar = 3.14159; char chrVar = 'A'; boolean blnVar = true; System.out.println(intVar); System.out.println(dblVar); System.out.println(chrVar); System.out.println(blnVar); System.out.println(); }

43 // Java2021.java // This program demonstrates how Java and arrays are // displayed when only the object identifier is printed. public class Java2021 { public static void main (String args[]) { System.out.println("\nJava2021.java\n"); int intList[] = {11,22,33,44,55,66,77,88,99}; System.out.println("intList: " + intList); System.out.println(); double dblList[] = {1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9}; System.out.println("dblList: " + dblList); System.out.println(); String strList[] = {"Tom","Joe","Sue","Meg"}; System.out.println("strList: " + strList); System.out.println(); }

44 Java2021 Graphic intList @16f0472 dblList @18d107f 16f0472 11 18d107f 1.1 strList @3b0eb0 3b0eb0 Tom

45 // Java2022.java // In this program the user-defined class uses the method inherited from the // class. The class method returns an actual string representation of // the object value, which is a memory address. public class Java2022 { public static void main (String args[]) { System.out.println("\nJava2022.java\n"); Student student1 = new Student("Tom",21,3.85); Student student2 = new Student("Joe",17,3.65); Student student3 = new Student("Sue",18,2.85); Student student4 = new Student("Meg",19,3.90); System.out.println("student1: " + student1); System.out.println("student2: " + student2); System.out.println("student3: " + student3); System.out.println("student4: " + student4); } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g){ name = n; age = a; gpa = g; } }

46 The Original toString Method print and println request display instructions from the toString method. Method toString is defined by the Object class. The Object class is the superclass for all Java classes. This means that every class has access to the toString method. The toString method, as defined by the Object class, returns the actual string representation values of all the primitive types like int, double, char and boolean. toString returns the class name followed by the memory reference of any variable object.

47 The Object Class “The Big Mamma Class Up in the Sky” toString equals

48 // Java2023.java // This program demonstrates behaves differently for the // class. Note that "referenced" values are displayed, not the references. import java.util.ArrayList; public class Java2023 { public static void main (String args[]) { System.out.println("\nJava2023.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: " + names); System.out.println(); }

49 // Java2024.java.java // The method of an ArrayList object displays the contents of the // object, but the non-Java class objects display memory addresses. import java.util.ArrayList; public class Java2024 { public static void main (String args[]) { System.out.println("\nJava2024.java\n"); ArrayList students = new ArrayList(); students.add(new Student("Tom",21,3.85)); students.add(new Student("Joe",17,3.65)); students.add(new Student("Sue",18,2.85)); students.add(new Student("Meg",19,3.90)); System.out.println("students: " + students); System.out.println(); } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g){ name = n; age = a; gpa = g; } }

50 // Java2025.java. // This program examples shows that manages to handle objects of objects // very nicely. In this case you see a display of an object or objects. import java.util.ArrayList; public class Java2025 { public static void main (String args[]) { System.out.println("\nJava2025.java\n"); ArrayList cats = new ArrayList(); cats.add("Lions"); cats.add("Tigers"); ArrayList swimmers = new ArrayList(); swimmers.add("Whales"); swimmers.add("Dolphins"); ArrayList primates = new ArrayList(); primates.add("Gorillas"); primates.add("Chimpanzees"); ArrayList mammals = new ArrayList(); mammals.add(cats); mammals.add(swimmers); mammals.add(primates); System.out.println(mammals); System.out.println(); }

51 ArrayList and toString ArrayList objects display the actual individual array elements and not the memory reference of the object. The output format looks like: [Tom, Sue, Joe, Kathy] This means that the toString method is redefined for the ArrayList class or some superclass of ArrayList.

52 // Java2026.java // This program demonstrates defining a method // in the class so that it displays the name field of a object. import java.util.ArrayList; public class Java2026 { public static void main (String args[]) { System.out.println("\nJava2026.java\n"); Student student1 = new Student("Kathy Alexander",21,3.75); Student student2 = new Student("Peter VanVliet",18,2.265); System.out.println(student1.toString()); System.out.println(student2.toString()); System.out.println(); } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; } public String toString() { return name; } }

53 // Java2027.java // This program is almost identical to the previous program. // This time the method is not called by any object. Yet the result // is the same because uses the string representation of for its output. import java.util.ArrayList; public class Java2027 { public static void main (String args[]) { System.out.println("\nJava2027.java\n"); Student student1 = new Student("Kathy Alexander",21,3.75); Student student2 = new Student("Peter VanVliet",18,2.265); System.out.println(student1); System.out.println(student2); System.out.println(); } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; } public String toString() { return name; } }

54 // Java2028.java // This program demonstrates "redefining the method in the // class so that it displays every field of a object. // Note how this implementation resembles the format. import java.util.ArrayList; public class Java2028 { public static void main (String args[]) { System.out.println("\nJava2028.java\n"); Student student1 = new Student("Kathy Alexander",21,3.475); Student student2 = new Student("Peter VanVliet",18,2.265); System.out.println(student1); System.out.println(student2); System.out.println(); } class Student { private String name; private int age; private double gpa; public Student(String n, int a, double g) { name = n; age = a; gpa = g; } public String toString(){ return "[" + name + "," + age + "," + gpa + "]"; } }

55 class Person { private String name; private int age; private char gender; private double salary; public Person(String n, int a, char g, double s) { name = n; age = a; gender = g; salary = s; } public String toString() { return "[" + name + ", " + age + ", " + gender + ", " + salary + "]"; } Person class used in the next several programs

56 // Java2029.java // This program tries to compares 2 person objects with the == operator. // This does not work because the == operator only checks the shallow value. // It also does not give us a way to determine how we will check for equality. import java.util.ArrayList; public class Java2029 { public static void main (String args[]) { System.out.println("\nJava2029.java\n"); Person tom = new Person("Tom Jones",36,'M',40000); Person sue = new Person("Sue Smith",29,'F',50000); Person bob = new Person("Bob Brown",40,'M',50000); System.out.println(tom); System.out.println(sue); System.out.println(bob); System.out.println(); if (tom == sue) System.out.println("Tom and Sue are equal."); else System.out.println("Tom and Sue are not equal."); if (tom == bob) System.out.println("Tom and Bob are equal."); else System.out.println("Tom and Bob are not equal."); if (sue == bob) System.out.println("Sue and Bob are equal."); else System.out.println("Sue and Bob are not equal."); }

57 Java2029 Graphic tom @16f0472 bob @18d107f 16f0472 Tom Jones36 $40,000.00‘M’ sue @3b0eb0 18d107f Sue Smith29 $50,000.00‘F’ 3b0eb0 Bob Brown40 $50,000.00‘M’

58 // Java2030.java // This program tries to compare 2 person objects with the equals method. This also does not work // because we have not "redefined" the equals method for the Person class, and we are simply // inheriting the equals method from the Object class, which only checks the shallow value. import java.util.ArrayList; public class Java2030 { public static void main (String args[]) { System.out.println("\nJava2030.java\n"); Person tom = new Person("Tom Jones",36,'M',40000); Person sue = new Person("Sue Smith",29,'F',50000); Person bob = new Person("Bob Brown",40,'M',50000); System.out.println(tom); System.out.println(sue); System.out.println(bob); System.out.println(); if (tom.equals(sue)) System.out.println("Tom and Sue are equal."); else System.out.println("Tom and Sue are not equal."); if (tom.equals(bob)) System.out.println("Tom and Bob are equal."); else System.out.println("Tom and Bob are not equal."); if (sue.equals(bob)) System.out.println("Sue and Bob are equal."); else System.out.println("Sue and Bob are not equal."); }

59 Java2030 Graphic tom @16f0472 bob @18d107f sue @3b0eb0 16f0472 Tom Jones36 $40,000.00‘M’ 18d107f Sue Smith29 $50,000.00‘F’ 3b0eb0 Bob Brown40 $50,000.00‘M’

60 // Java2031.java // This program properly compares 2 person objects with the redefined equals method. // It chooses to define "equality" solely based on a Person's salary, which may be // overly capitalistic, but still makes a point. import java.util.ArrayList; public class Java2031 { public static void main (String args[]) { System.out.println("\nJava2031.java\n"); Person tom = new Person("Tom Jones",36,'M',40000); Person sue = new Person("Sue Smith",29,'F',50000); Person bob = new Person("Bob Brown",40,'M',50000); System.out.println(tom); System.out.println(sue); System.out.println(bob); System.out.println(); if (tom.equals(sue)) System.out.println("Tom and Sue are equal."); else System.out.println("Tom and Sue are not equal."); if (tom.equals(bob)) System.out.println("Tom and Bob are equal."); else System.out.println("Tom and Bob are not equal."); if (sue.equals(bob)) System.out.println("Sue and Bob are equal."); else System.out.println("Sue and Bob are not equal."); }

61 class Person { private String name; private int age; private char gender; private double salary; public Person(String n, int a, char g, double s) { name = n; age = a; gender = g; salary = s; } public String toString() { return "[" + name + ", " + age + ", " + gender + ", " + salary + "]"; } public boolean equals(Person temp) { return salary == temp.salary; }

62 // Java2032.java // This program is almost identical to the previous one. The only difference is // the addition of the "this" poniter in the equals method to help distinguish the 2 objects. class Person { private String name; private int age; private char gender; private double salary; public Person(String n, int a, char g, double s) { name = n; age = a; gender = g; salary = s; } public String toString() { return "[" + name + ", " + age + ", " + gender + ", " + salary + "]"; } public boolean equals(Person temp) { return this.salary == temp.salary; }

63 Java2031 & 32 Graphic tom @16f0472 bob @18d107f sue @3b0eb0 16f0472 Tom Jones36 $40,000.00‘M’ 18d107f Sue Smith29 $50,000.00‘F’ 3b0eb0 Bob Brown40 $50,000.00‘M’

64 // Java2033.java // This program defines equality differently from the previous programs. Now all data fields must // match for 2 Person objects to be considered equal. NOTE: It is not uncommon for the equals // method from one class to call the equals method from another class. class Person { private String name; private int age; private char gender; private double salary; public Person(String n, int a, char g, double s) { name = n; age = a; gender = g; salary = s; } public String toString() { return "[" + name + ", " + age + ", " + gender + ", " + salary + "]"; } public boolean equals(Person temp) { return this.name.equals(temp.name) && this.age == temp.age && this.gender == temp.gender&& this.salary == temp.salary; }

65 Java2033 Graphic tom @16f0472 bob @18d107f sue @3b0eb0 16f0472 Tom Jones36 $40,000.00‘M’ 18d107f Sue Smith29 $50,000.00‘F’ 3b0eb0 Bob Brown40 $50,000.00‘M’

66 // Java2034.java // This program defines equality using a line from the Constitution of the United States. class Person { private String name; private int age; private char gender; private double salary; public Person(String n, int a, char g, double s) { name = n; age = a; gender = g; salary = s; } public String toString() { return "[" + name + ", " + age + ", " + gender + ", " + salary + "]"; } public boolean equals(Person temp) { return true; // "All men (and women) are created equal." }

67 // Java2035.java // This program demonstrates that the equals method has already be redefined for the ArrayList class import java.util.ArrayList; public class Java2035 { public static void main(String args[]) { System.out.println("Java2035.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(); // note required type casting System.out.println(); System.out.println("names2 contains " + names2); System.out.println(); if (names1.equals(names2)) System.out.println("names1 and names2 are equal."); else System.out.println("names1 and names2 are not equal."); 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(); if (names1.equals(names2)) System.out.println("names1 and names2 are equal."); else System.out.println("names1 and names2 are not equal."); }

68 ArrayList and equals Two ArrayList objects are considered equal if they are the same size, and they store the same information at each and every index.


Download ppt "Introduction Chapter 12 introduced the array data structure. Historically, the array was the first data structure used by programming languages. With."

Similar presentations


Ads by Google