J
Joseph Dionne
Sudsy said:I've never heard of such a rule. According to the javadocs for
Object#hashCode:
Objecte.hashCode does not work like Interger.hashCode.
Integer provides it's own hashCode method that returns the value. This
allows you to put an Integer object into a list and find it again via
another Integer object.
The Object.hashCode method will produce two different hash values for
two Integer objects even if each Integer object is equal.
Integer Int1 = new Integer(123);
Integer Int2 = new Integer(123);
thus Int1.hashCode() == Int2.hashCode() and Int1.equals(Int2) are true
However a replacement Integer class that does not implement hashCode,
relying on Object.hashCode will result in two unique hash values.
Example; (uncomment the Int.equals method to see the difference)
public class tJava
{
public static void main(String[] args) throws Exception
{
Object Int1 = new Integer(123);
Object Int2 = new Integer(123);
if (Int1.hashCode() == Int2.hashCode())
System.out.println("hashCode are equal");
else
System.out.println("hashCode are unequal");
if (Int1.equals(Int2))
System.out.println("they are equal");
else
System.out.println("they are unequal");
if (((Object)Int1).hashCode() == ((Object)Int2).hashCode())
System.out.println("hashCode are equal");
else
System.out.println("hashCode are unequal");
Int1 = new Int(123);
Int2 = new Int(123);
if (Int1.hashCode() == Int2.hashCode())
System.out.println("hashCode are equal");
else
System.out.println("hashCode are unequal");
if (Int1.equals(Int2))
System.out.println("they are equal");
else
System.out.println("they are unequal");
if (((Object)Int1).hashCode() == ((Object)Int2).hashCode())
System.out.println("hashCode are equal");
else
System.out.println("hashCode are unequal");
}
}
class Int
{
private int value;
public Int(int v) { value = v; }
public int intValue() { return(value); }
// public boolean equals(Object o)
// {
// if (o instanceof Int) return(value == ((Int)o).value);
// return(false);
// }
}