Hi,
I am trying to remove an object from a array list by passing in the object to be removed.
I have a equals method as well. But somehow its not woking. The equals method is not getting picked.
Please suggest whats wrong
Heres my code:
import java.util.*; class Dummy { int x; Dummy(int y) { x=y; } public boolean equals(Dummy o) { if(o.x==this.x) return true; return false; } public String toString() { return Integer.toString(x); } } class CollTest { public static void main(String args[]) { ArrayList al = new ArrayList(); System.out.println("Initial size of al: " +al.size()); // add elements to the array list al.add(new Dummy(5)); al.add(new Dummy(6)); al.add(new Dummy(7)); System.out.println("Size of al after additions: " +al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove(new Dummy(5)); System.out.println("Size of al after deletions: " +al.size()); System.out.println("Contents of al: " + al); } }
Output is:
Initial size of al: 0
Size of al after additions: 3
Contents of al: [5, 6, 7]
Size of al after deletions: 3
Contents of al: [5, 6, 7]