According to the hashCode
/equals
contract if two objects are equal the must have the same hashCode
- at least it is how I know it. Consider the following implementation:
package Happy;
import java.time.LocalDate;
class MyClass
{
private int id;
public int getId()
{
return id;
}
public MyClass(int id)
{
this.id = id;
}
public int hashCode()
{
return LocalDate.now().getYear() + getId();
}
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyClass other = (MyClass) obj;
if (hashCode() != other.hashCode())
return false;
return true;
}
}
public class HappyNewYear
{
public static void main(String[] args) {
MyClass my = new MyClass(0);
if (my.hashCode() != my.hashCode()) System.out.println("Happy New Year!");
}
}
With little modifications we can get a less extreme variant:
public int hashCode()
{
return return (int) (System.nanoTime() + getId());
}
I tested it (not with the getYear
though), and the condition were true (the hashCodes
were not equal).
Is it legal if the hashCode
changes over time even if the object's fields are unmodified? I could not find any resources about this specific implementation. I know about the problem with collections, but my question is if the hashCode implementation is legal according to the contract/spec.
PS: It is a challenge question, I answered that it's not legal, but I am not sure since I at first look at the code, equals
and hashCode
are satisfiyng the simple contract.