I am having a problem removing duplicate objects using LinkedHashSet. I created a
test object called MyDimension. I have overridden the equals method and the hashcode method. I think I have overridden them correctly but I may have made a mistake. I get the correct behavior when I call the equals method of MyDimension when comparing two objects, so I don't think there is anything wrong there. I added print statements to the hashcode method and it shows the same hashcode value for the two objects that contain the same data. It there something I am missing?
I just can't figure out why the ArrayList passed to LinkedHashSet still have duplicates. I have included the MyDimension.java and Test4.java.
public class MyDimension {
double length;
double width;
public MyDimension(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public
String toString() {
return new String("Length = " + length + " Width = "+ width);
}
public boolean equals(MyDimension obj) {
if (obj != null && (obj.getClass().equals(this.getClass()))) {
return (width == obj.getWidth()) && (length == obj.getLength());
}
return false;
}
public int hashCode() {
long tempValue = (Double.doubleToLongBits(this.length) + Double.doubleToLongBits(this.width));
System.out.println("HASHCODE CALLED VALUE IS " + tempValue);
int tempInt = (int)(tempValue^(tempValue >>> 32));
System.out.println("HASHCODE CALLED VALUE IS " + tempInt);
return tempInt;
}
}
import java.util.List;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.LinkedHashSet;
public class Test4 {
public static void main(String args[]) {
MyDimension a = new MyDimension(21.1, 20.1);
MyDimension b = new MyDimension(11.5, 10.5);
MyDimension c = new MyDimension(21.1, 20.1);
MyDimension d = new MyDimension(5.4, 3.4);
ArrayList<MyDimension> myList = new ArrayList<MyDimension>();
myList.add(a);
myList.add(b);
myList.add(c);
myList.add(d);
LinkedHashSet<MyDimension> set = new LinkedHashSet<MyDimension>();
set.addAll(myList);
myList.clear();
myList.addAll(set);
if (a.equals(b)) {
System.out.println("A equals B");
}
else {
System.out.println("A does not equal B");
}
if (a.equals(c)) {
System.out.println("A equals C");
}
else {
System.out.println("A does not equal C");
}
for (int i = 0; i < myList.size(); i++) {
System.out.println( myList.get(i).toString() );
}
}
}