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

Slides:



Advertisements
Similar presentations
The ArrayList Class and the enum Keyword
Advertisements

Generics and the ArrayList Class
Chapter 7 – Arrays.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Arrays And ArrayLists - S. Kelly-Bootle
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Review of Simple/Primitive Data Types A simple/primitive data type can store only one single value. This means an int can only store one integer. A double.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Review of Math Class Methods abssqrt minmax powround ceilfloor.
ArrayList, Multidimensional Arrays
Algorithm Definition An algorithm is a step-by-step solution to a problem.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Introduction Chapter 12 introduced the array data structure. Historically, the array was the first data structure used by programming languages. With.
First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java programs,
Program Flow Program Flow follows the exact sequence of listed program statements, unless directed otherwise by a Java control structure.
Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
Java Arrays  Java has a static array capable of multi-dimensions.  Java has a dynamic array, which is also capable of multi-dimensions.  The ArrayList.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Queue Definition A queue is a data structure with elements of the same type. Queue elements can only be entered at one end of the queue, called the back,
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Review of Math Class Methods abssqrt minmax powround ceilfloor.
Visual Classes 1 Class: Bug 5 Objects: All Bug Objects.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
CSE 1201 Object Oriented Programming ArrayList 1.
// Java2101.java This program tests the features of the class. public class Java2101 { public static void main (String args[]) { System.out.println("\nJAVA2101.JAVA\n");
Review of Simple/Primitive Data Types A simple/primitive data type can store only one single value. This means an int can only store one integer. A.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Programs & Data Files Notes Data information processed by word processing, spreadsheet or other application programs are stored as data files. Java.
First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.
The ArrayList Data Structure Standard Arrays at High Speed!
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Java Arrays  Java has a static array capable of easy multi-dimensions.  Java has a dynamic array, which is also capable of multi-dimensions, but it.
First Data Structure Definition A data structure is a data type whose components are smaller data structures and/or simple data types.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
Algorithm Definition An algorithm is a step-by-step solution to a problem.
Exposure Java 2011 APCS Edition
Chapter 7 – Arrays and Array Lists
MC Question Strategies
Exposure Java 2014 APCS Edition
PowerPoint Presentation From Materials Created
with the ArrayList Class
Exposure Java 2015 AP®CS Edition
Section 11.1 Introduction to Data Structures.
Exposure Java 2015 Pre-AP®CS Edition Chapter 12 Slides String Methods
Section 6.2 Classes & Objects.
Presentation transcript:

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

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

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

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

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.

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

ArrayList Access ArrayList objects cannot be accessed with an index [ ] operator, like a Java static array. All access is performed with ArrayList methods. ACCESS DENIED!

ArrayList Method add names.add("Tom"); The add method allocates space for the newly enlarged array and then stores the new array element at the end of the ArrayList object.

Displaying ArrayList Elements ArrayList elements can be accessed with various methods. It is possible to display all the elements inside square brackets, separated by commas by using the print method. System.out.println(names); [Isolde, John, Greg, Maria, Heidi]

// Java2005.java // This program uses the method to determine the number of elements // in an <ArrayList object. import java.util.ArrayList; public class Java2005 { public static void main(String args[]) { System.out.println(); System.out.println("Java2005.java\n"); ArrayList names = new ArrayList(); names.add("Isolde"); names.add("John"); names.add("Greg"); names.add("Maria"); names.add(new String("Heidi")); System.out.println("names contains " + names); System.out.println(); System.out.println("There are " + names.size() + " elements in the names object."); System.out.println(); }

ArrayList Method size int count = names.size(); The size method returns the number of elements of the ArrayList object names. Remember Strings and Java static arrays use length instead of size.

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

ArrayList Method get System.out.println(names.get(3)); The get method accesses a specified array element. The parameter of the get method is the index of the ArrayList object and starts at 0. Any attempt to access an element at a non-existing index results in an IndexOutOfBoundsException error.

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

ArrayList Method set names.set(4,"Tom"); The set method uses the first parameter as the index location to find an array element and then replaces it with the value of the second set parameter. You will get an error if you try to access an index location, which has not been allocated yet.

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

ArrayList Method remove names.remove(3); The remove method removes the array element at the index location of its parameter and decreases the object size by one array element. You will get an error if you try to access an index location, which does not exist.

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

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.

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

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

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

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

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

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

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

ArrayList Methods contains & indexOf System.out.println(names.contains("Greg")); System.out.println(names.indexOf("Greg")); The contains method returns true if the parameter value is an element of the names array object and false otherwise. The indexOf method returns the index of the parameter if the parameter is an element of the names object and -1 otherwise.

Primitive Type Warning Java primitive types like int, double, char and boolean must be converted to object before they can be added to an ArrayList object.

// Java2015.java // This program demonstrates that it is possible to store integers in an object // with a "wrapper" class. It is easier to use a regular array to store primitive data elements. import java.util.ArrayList; public class Java2015 { public static void main(String args[]) { System.out.println(); System.out.println("Java2015.java\n"); ArrayList numbers = new ArrayList(); numbers.add(new Integer(12345)); numbers.add(new Integer(23451)); numbers.add(new Integer(34512)); numbers.add(new Integer(45123)); numbers.add(new Integer(51234)); for (int k = 0; k < numbers.size(); k++) System.out.println((Integer) numbers.get(k)); System.out.println(); }

// Java2016.java // This program demonstrates that integer stored into an object cannot // be added with direct access, like static Java array elements. import java.util.ArrayList; import java.util.Random; public class Java2016 { public static void main(String args[]) { System.out.println("Java2016.java\n"); Random rand = new Random(12345); ArrayList numbers = new ArrayList(); for (int k = 1; k <= 48; k++) { int rndInt = (rand.nextInt(900) + 100); numbers.add(new Integer(rndInt)); } int sum = 0; for (int k = 0; k < numbers.size(); k++) sum += numbers.get(k); System.out.println("Sum: " + sum); }

// Java2017.java // This program demonstrates how to access the "int" value within an "integer" object. import java.util.ArrayList; import java.util.Random; public class Java2017 { public static void main(String args[]) { System.out.println("Java2017.java\n"); Random rand = new Random(12345); ArrayList numbers = new ArrayList(); for (int k = 1; k <= 48; k++) { int rndInt = (rand.nextInt(900) + 100); numbers.add(new Integer(rndInt)); } int sum = 0; for (int k = 0; k < numbers.size(); k++) { Integer temp = (Integer) numbers.get(k); sum += temp.intValue(); } System.out.println("Sum: " + sum); System.out.println(); }

// Java2018.java // This program takes an earlier program from the Algorithm chapter, implemented // with a array and converts it to an ArrayList implementation. import java.io.*; import java.util.*; public class Java2018 { public static void main(String args[]) throws IOException { System.out.println("Java2018.java\n"); List list = new List(); list.getList(); list.pause(); list.display(); list.pause(); list.bubbleSort(); list.display(); System.out.println(); } class Person { public String name; public int age; public double gpa; Person(String n, int a,double g) { name = n; age = a; gpa = g; } }

class List { private ArrayList students; public List() { students = new ArrayList(); } public void getList() throws IOException { System.out.println("\nRetrieving Students.dat\n"); FileReader inFile = new FileReader("Students.dat"); BufferedReader inStream = new BufferedReader(inFile); String s1,s2,s3; while( ((s1 = inStream.readLine()) != null) && ((s2 = inStream.readLine()) != null) && ((s3 = inStream.readLine()) != null) ) { String name = s1; int age = Integer.parseInt(s2); double gpa = Double.parseDouble(s3); students.add(new Person(name,age,gpa)); } inStream.close(); }

public void display() { System.out.println("\nDISPLAYING LIST ELEMENTS"); for (int k = 0; k < students.size(); k++) { Person person = (Person) students.get(k); System.out.println(person.name + "\t\t" + person.age + "\t\t" + person.gpa); } public void pause() { Scanner input = new Scanner(System.in); String dummy; System.out.print("\nPress to continue ===>> "); dummy = input.nextLine(); }

private void swap(int x, int y) { Person temp = (Person) students.get(x); students.set(x,students.get(y)); students.set(y,temp); } public void bubbleSort() { Person p, q; for (int s = 1; s < students.size(); s++) for (int t = 0; t < students.size()-s; t++) { p = (Person) students.get(t); q = (Person) students.get(t+1); if (p.gpa < q.gpa) swap(t,t+1); }

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

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

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

Java2021 Graphic 16f d107f 1.1 3b0eb0 Tom

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

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.

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

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

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

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

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.

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

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

// 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 + "]"; } }

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

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

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

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

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

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

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

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

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

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

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

// 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." }

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

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.