0
HashSet hs = new HashSet();
hs.add(1000);
hs.add(new Integer(1000));
System.out.println(hs);

The above code prints [1000] but I have used the new operator which shall create a new object in memory and hence the hash code must be different ,so should it not have two values in hashset?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • "*...I have used the new operator which shall create a new object in memory and hence the hash code must be different*" if objects carry some state then hash can't be based on memory address. In case of Integer hash is simply value it holds so hash for `1000` is `1000`, regardless how you create that object. – Pshemo May 02 '18 at 13:06
  • 1
    In the duplicated question, go here: https://stackoverflow.com/a/11890876/1531124 ... the hashcode of an Integer object is its value. So obviously two Integer objects of the same value are A) equal and B) have the same hashcode. And that is **all** that matters to the HashSet – GhostCat May 02 '18 at 13:10

3 Answers3

4

I have used the new operator which shall create a new object in memory and hence the hash code must be different

That assumption is not correct. The default hashCode implementation returns a different hash for different instances, but that is not a requirement. In many cases you actually want different instances to return the same hashCode (calculated from instance members) to be able to compare instances for equality.

From the documentation of Integer hashCode:

Returns: a hash code value for this object, equal to the primitive int value represented by this Integer object.

If you actually want a map that doesn't use equals/hashCode, take a look at the IdentityHashMap class.

kapex
  • 28,903
  • 6
  • 107
  • 121
0

Integer's hashcode() method returns hash code value for the object which is equal to the internally stored primitive int value, which in your case is 1000.

0

To understand it better lets make a small test, lets find the hashCode of this cases :

int     i1 = 1000;
Integer i2 = 1000;
Integer i3 = new Integer(1000);

System.out.println(Integer.valueOf(i1).hashCode());
System.out.println(i2.hashCode());
System.out.println(i3.hashCode());

All the cases return the same hashCode.

Outputs

1000
1000
1000

For that you get one value in the Set and not two like you expected.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140