I want to store data in a map, with key unicity, but I would like the map to use the equals method of my key class.
It seems that HashMap doesn't use the equals method (I may be wrong, if so my tests are wrong).
My problem here is that the map use hashCode to check for duplicate, and I would like a map implementation that use equals.
I am storing timestamp in the key, and would like to make it so that 2 keys are equals if there timestamp difference does not exceed a defined amount (let say 1000 ms).
Edit : code
public class CleanKey
{
private DateTime start;
private DateTime end;
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((end == null) ? 0 : end.hashCode());
result = prime * result + ((start == null) ? 0 : start.hashCode());
return result;
}
public boolean equals(Object obj)
{
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
CleanKey other = (CleanKey) obj;
if(end == null)
{
if(other.end != null)
return false;
}
else if(Math.abs(Millis.millisBetween(end, other.end).getMillis()) > 1000)
return false;
if(start == null)
{
if(other.start != null)
return false;
}
else if(Math.abs(Millis.millisBetween(start, other.start).getMillis()) > 1000)
return false;
return true;
}
}
It seems that HashMap doesn't use the equals method (I may be wrong, if so my tests are wrong).
It does use equals
, but it uses hashCode
first. It will only bother calling equals
on keys with the same hash code - that's how it manages to be efficient. That's not a problem so long as your hashCode
and equals
method obey the contract specified in java.lang.Object
.
I am storing timestamp in the key, and would like to make it so that 2 keys are equals if there timestamp difference does not exceed a defined amount (let say 1000 ms).
You can't do that. It violates the contract of equals, because you can't have transitivity. Suppose we have three keys x, y, and z with the following timestamps:
x 400
y 1200
z 2000
By your description, x.equals(y)
would be true, y.equals(z)
would be true, but x.equals(z)
would be false, thus violating the contract of Object.equals
.
The equals method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
- For any non-null reference value x, x.equals(null) should return false.
See more on this question at Stackoverflow