import java.util.ArrayList;
public class ArrayListTester {
public static void main(String args []){
// create an ArrayList with a capacity of 20
ArrayList<Integer> a = new ArrayList<Integer>(20);
System.out.println(a);
a.add(10);
System.out.println(a);
// can we do the following?
a.add(0,5);
System.out.println(a);
// how about:
a.add(1,5);
System.out.println(a);
// and let's try now:
//a.add(10,5);
// create some instances of StoresX
StoresX x1 = new StoresX(42);
StoresX x2 = new StoresX(10);
StoresX x3 = new StoresX(10);
// notice that x3 stores the same value as x2.
// by overloading the standard java .equals method in
// StoresX we get that
System.out.println("x2 equals x3? " + x2.equals(x3));
// evaluates to true
// this isn't true using the default implementation of
// .equals. Why?
ArrayList<StoresX> xarray = new ArrayList<StoresX>();
xarray.add(x1);
xarray.add(x2);
// to check if there is an object like x3 in the ArrayList:
System.out.println(xarray.indexOf(x3));
// note that indexOf iteratively applies the .equals until
// if finds an object that is identical to the given object
// (identical under the definition provided by the .equals method).
}
}
public class ArrayListTester {
public static void main(String args []){
// create an ArrayList with a capacity of 20
ArrayList<Integer> a = new ArrayList<Integer>(20);
System.out.println(a);
a.add(10);
System.out.println(a);
// can we do the following?
a.add(0,5);
System.out.println(a);
// how about:
a.add(1,5);
System.out.println(a);
// and let's try now:
//a.add(10,5);
// create some instances of StoresX
StoresX x1 = new StoresX(42);
StoresX x2 = new StoresX(10);
StoresX x3 = new StoresX(10);
// notice that x3 stores the same value as x2.
// by overloading the standard java .equals method in
// StoresX we get that
System.out.println("x2 equals x3? " + x2.equals(x3));
// evaluates to true
// this isn't true using the default implementation of
// .equals. Why?
ArrayList<StoresX> xarray = new ArrayList<StoresX>();
xarray.add(x1);
xarray.add(x2);
// to check if there is an object like x3 in the ArrayList:
System.out.println(xarray.indexOf(x3));
// note that indexOf iteratively applies the .equals until
// if finds an object that is identical to the given object
// (identical under the definition provided by the .equals method).
}
}
And here's the code for the StoresX class (look very carefully at the .equals method):
public class StoresX {
private int x;
public StoresX(int x){
this.x = x;
}
public boolean equals(Object other){
return this.x == ((StoresX)other).x;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
