I have a class M with hashCode() and equals() generated by Eclipse (please see below).
Two lists with equal M's are equal, Two sets with equal M's are not equal.
Is this a bug in deepEquals() or am I confused?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
class M {
@Override public int hashCode() {
final int prime=31;
int result=1;
result=prime*result+Arrays.hashCode(b);
return result;
}
@Override public boolean equals(Object obj) {
if(this==obj) return true;
if(obj==null) return false;
if(getClass()!=obj.getClass()) return false;
M other=(M)obj;
if(!Arrays.deepEquals(b,other.b)) return false;
return true;
}
int[][] b=new int[3][3];
}
public class SetEquality {
static List<Object> list(Object o) {
ArrayList<Object> l=new ArrayList<>();
l.add(o);
return l;
}
static Set<Object> set(Object o) {
Set<Object> l=new LinkedHashSet<>();
l.add(o);
return l;
}
public static void main(String[] args) {
M f=new M();
M g=new M();
List<Object> listWithF=list(f);
List<Object> listWithG=list(g);
System.out.println("lists: "+listWithF.equals(listWithG));
Set<Object> setWithF=set(f);
Set<Object> setWithG=set(g);
System.out.println("sets: "+setWithF.equals(setWithG));
}
}
The problem is that your objects aren't returning equal hashcodes. You need to use Arrays.deepHashCode()
instead (see e.g. http://ideone.com/qPyWLh).
This appears to be a known bug in Eclipse: https://bugs.eclipse.org/bugs/show_bug.cgi?id=422717.