Wednesday, March 26, 2008

Java... what a hell?!?[2]

Following the last post about Java (here) I tell another weird Java behaviour that costed my a work day to figure it out.

//--- snippet ---//
double tst1[] = new double[]{1.0, 2.0};
double tst2[] = new double[]{1.0, 2.0};
Collection lst1 = new ArrayList();
Collection lst2 = new ArrayList();

for (double val : tst1) {
lst1.add(val);
}
for (double val : tst2) {
lst2.add(val);
}
// array version
System.out.println(tst1.hashCode());
System.out.println(tst2.hashCode());
System.out.println(tst1.hashCode() == tst2.hashCode());
System.out.println(tst1 == tst2);
// collection version
System.out.println(lst1.hashCode());
System.out.println(lst2.hashCode());
System.out.println(lst1.hashCode() == lst2.hashCode());
System.out.println(lst1 == lst2); // false
System.out.println(lst1.equals(lst2)); // true
//--- snippet ---//


Try the snippet above and you will see what I mean. I always thought that arrays would be at least hash consistent, i.e., implementing the collection specification on Java.

Once again Java had proven my intuition wrong. By the way, my output from the above snippet is the following:

//--- snippet ---//
4072869
1671711
false
false
-32504895
-32504895
true
false
true
//--- snippet ---//

No comments: