There are two sets which have the same single element.
Set<Activity> a = new HashSet<Activity>();
a.add(new Activity("X", 1, 2));
Set<Activity> b = new HashSet<Activity>();
b.add(new Activity("X", 1, 2));
return a.containsAll(b); //gives false??
the containsAll method returns false when in fact the sets are identical?
I have read answers to similar questions one of which is HashSet contains problem with custom objects, HashSet contains method, strange behavior and I understand how HashSet works. You compute the hash to a bucket and then search for the object using the overridden equals() method.
The activity class is implemented this way:
public class Activity implements Comparable<Activity> {
private final double maxDuration;
private final double normalDuration;
private final String label;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((label == null) ? 0 : label.hashCode());
long temp;
temp = Double.doubleToLongBits(maxDuration);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(normalDuration);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Activity other = (Activity) obj;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
if (Double.doubleToLongBits(maxDuration) != Double
.doubleToLongBits(other.maxDuration))
return false;
if (Double.doubleToLongBits(normalDuration) != Double
.doubleToLongBits(other.normalDuration))
return false;
return true;
}
public Activity(String label, double d, double e) {
this.maxDuration = e;
this.normalDuration = d;
this.label = label;
}
}
The inputs to the hashCode and equals functions (as shown above) are the same, the functions are deterministic therefore why does this happen? There is definitely no way that the Activity objects are being changed as I explicitly made them immutable. So I am completely lost as to why this happens.
Thanks in advance for any help.