+ All Categories
Home > Documents > Introduction Chapter 12 introduced the array data structure. Historically, the array was the first...

Introduction Chapter 12 introduced the array data structure. Historically, the array was the first...

Date post: 02-Jan-2016
Category:
Upload: irma-francis
View: 220 times
Download: 1 times
Share this document with a friend
Popular Tags:
78
Transcript

IntroductionChapter 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 LimitationsThe 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 <ArrayList> class with the <add> 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 AccessArrayList 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 <size>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 sizeint 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 <ArrayList> object// with the <get> 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 <set> method of the <ArrayList> 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 <remove> method of the <ArrayList> 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 <add> method of the <ArrayList> 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(2nd 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 <clear> method to remove all the // array elements and the <isEmpty> 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 <ArrayList> 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 <ArrayList> 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 <ArrayList> 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 constructorSystem.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 <ArrayList> object with // the <clone> 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

Isolde John Greg Maria Heidi

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 Isolde John Greg Maria Heidi

names2 Isolde John Greg Maria Heidi

Deep Copy

// Java2014.java// This program uses the <contains> method to determine if some object is an element// in an <ArrayList> object. It also uses the <indexOf> 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 Methodscontains & 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 <ArrayList> 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 <ArrayList> 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 <Person> 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 <Enter> 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 <String> 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 <int>, <double>, <char> and <boolean>// 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();

}}

// Java2021.java// This program demonstrates how Java <int> and <double> 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

intList

@16f0472

dblList

@18d107f

16f0472

11

18d107f

1.1

strList

@3b0eb0

3b0eb0

Tom

// Java2022.java// In this program the user-defined <Student> class uses the <toString> method inherited from the// <Object> class. The <Object> class <toString> 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 Methodprint 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”

toStringequals

// Java2023.java// This program demonstrates <toString> behaves differently for the <ArrayList>// 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 <toString> method of an ArrayList object displays the contents of the <ArrayList>// object, but the non-Java class <Student> 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 <toString> manages to handle objects of objects // very nicely. In this case you see a display of an <ArrayList> object or <ArrayList> 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 toStringArrayList 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 <toString> method// in the <Student> class so that it displays the name field of a <Student> 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 <toString> method is not called by any <Student> object. Yet the result // is the same because <println> uses the string representation of <toString> 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 <toString> method in the// <Student> class so that it displays every field of a <Student> object.// Note how this implementation resembles the <ArrayList> 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

tom

@16f0472

bob

@18d107f

16f0472Tom Jones 36

$40,000.00 ‘M’

sue

@3b0eb0

18d107fSue Smith 29

$50,000.00 ‘F’

3b0eb0Bob Brown 40

$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

tom

@16f0472

bob

@18d107f

sue

@3b0eb0

16f0472Tom Jones 36

$40,000.00 ‘M’

18d107fSue Smith 29

$50,000.00 ‘F’

3b0eb0Bob Brown 40

$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

tom

@16f0472

bob

@18d107f

sue

@3b0eb0

16f0472Tom Jones 36

$40,000.00 ‘M’

18d107fSue Smith 29

$50,000.00 ‘F’

3b0eb0Bob Brown 40

$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

tom

@16f0472

bob

@18d107f

sue

@3b0eb0

16f0472Tom Jones 36

$40,000.00 ‘M’

18d107fSue Smith 29

$50,000.00 ‘F’

3b0eb0Bob Brown 40

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

// Java2036.java// This program introduces automatic "boxing" and "unboxing".// In this example the simple <int> values are automatically converted// to <Integer> objects and <Integer> objects are converted to <int> values.

public class Java2036{

public static void main (String args[]){

System.out.println();System.out.println("Java2036.java\n");

///// JAVA 1.4 /////Integer num1 = new Integer(200); // boxes or wraps <int> value 200 inside an <Integer> objectint num2 = num1.intValue(); // unboxes or unwraps the <Integer> object into an <int> 200 value

System.out.println("num1 = " + num1);System.out.println();

///// JAVA 5.0 /////Integer num3 = 400; // automatically boxes 400 inside an <Integer> objectint num4 = num3; // automatically unboxes <Integer> object into an <int> 400 value

System.out.println("num4 = " + num4);System.out.println("\n\n");

}}

// Java2037.java// This program shows a practical example of "autoboxing".// Note how it is easier to add simple <int> values to an <ArrayList> object.import java.util.*; // necessary to use the <ArrayList> class.public class Java2037{

public static void main (String args[]){

System.out.println();System.out.println("Java2037.java\n");ArrayList list = new ArrayList();

///// JAVA 1.4 /////list.add(new Integer(100));list.add(new Integer(200));list.add(new Integer(300));System.out.println(list);

///// JAVA 5.0 /////list.add(400);list.add(500);list.add(600);System.out.println(list);System.out.println("\n\n");

}}

Autoboxing Observation

ArrayList objects cannot store primitive data values, even if it appears that int values are added directly to an ArrayList object.

With Java 5.0 the required boxing and unboxing are done automatically.

// Java2038.java// This program shows that automatic "unboxing" with <ArrayList> objects still requires the need for// casting. There is no automatic assumption that an <ArrayList> object stores an <Integer>.import java.util.*; // necessary to use the <ArrayList> class.public class Java2038{

public static void main (String args[]){

System.out.println();System.out.println("Java2038.java\n");ArrayList list = new ArrayList();

///// JAVA 1.4 /////list.add(new Integer(100));list.add(new Integer(200));list.add(new Integer(300));System.out.println(list);int num1 = ((Integer)list.get(2)).intValue();System.out.println("num1 = " + num1);System.out.println("\n\n");

///// JAVA 5.0 /////list.add(400);list.add(500);list.add(600);System.out.println(list);int num2 = ((Integer)list.get(4)); // <intValue> is not necessary, but casting isSystem.out.println("num2 = " + num2); System.out.println("\n\n");

}}

// Java2039.java// This program repeats the Java2038.java example.// This time typecasting is not necessary in line 31.import java.util.*; // necessary to use the <ArrayList> class.public class Tiger09{

public static void main (String args[]){

System.out.println();System.out.println("Java2039.java\n");

///// JAVA 1.4 /////ArrayList list1 = new ArrayList();list1.add(new Integer(100));list1.add(new Integer(200));list1.add(new Integer(300));System.out.println(list1);int num1 = ((Integer)list1.get(2)).intValue();System.out.println("num1 = " + num1);System.out.println("\n\n");

///// JAVA 5.0 /////// Note that <Integer> is specifiedArrayList<Integer> list2 = new ArrayList<Integer>();

list2.add(400); list2.add(500); list2.add(600);System.out.println(list2);int num2 = list2.get(2); // type casting is not necessary with genericsSystem.out.println("num2 = " + num2); System.out.println("\n\n");

}}

// Java2040.java// This program introduces the concept of a templated class. In this example you will observe that// three <ArrayList> objects are instantiated with three different object types.import java.util.*; // necessary to use the <ArrayList> class.public class Java2040{

public static void main (String args[]){

System.out.println();System.out.println("Java2040.java\n");///// JAVA 1.4 /////ArrayList list1 = new ArrayList();ArrayList list2 = new ArrayList();ArrayList list3 = new ArrayList();list1.add(new Integer(100));list2.add(new Double(200.123));list3.add("Generics");int val1 = ((Integer)list1.get(0)).intValue();double val2 = ((Double)list2.get(0)).doubleValue();String val3 = ((String)list3.get(0));System.out.println(val1 + "\n" + val2 + "\n" + val3 +"\n\n");

///// JAVA 5.0 /////ArrayList<Integer> list4 = new ArrayList<Integer>();ArrayList<Double> list5 = new ArrayList<Double>();ArrayList<String> list6 = new ArrayList<String>();list4.add(100);list5.add(200.123);list6.add("Generics");int val4 = list4.get(0);double val5 = list5.get(0);String val6 = list6.get(0);System.out.println(val4 + "\n" + val5 + "\n" + val6 +"\n\n");

}}


Recommended