-1

is that normal that I have the same hashcode for both ?? I'm confuse. I thought the hashcode was unique.

public static void main(String[] args) {
    HashMap<String, Integer> t = new HashMap<String, Integer>();

    t.put("one", 123);
    t.put("two", 123);

    System.out.println(t.get("one").hashCode());
    System.out.println(t.get("two").hashCode());
}

output

123
123
Kasun Kodagoda
  • 3,956
  • 5
  • 31
  • 54
user2037696
  • 1,055
  • 3
  • 16
  • 33

2 Answers2

0

Yes, 123 and 123 has the same hashcode because these are two Integers with the same int value:

t.get("one") // returns an Integer with an int value of 123
t.get("two") // returns an Integer with an int value of 123

From the docs (Integer.hashCode()):

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

When in doubt use the source:

     /**
  743        * Returns a hash code for this {@code Integer}.
  744        *
  745        * @return  a hash code value for this object, equal to the
  746        *          primitive {@code int} value represented by this
  747        *          {@code Integer} object.
  748        */
  749       public int hashCode() {
  750           return value;
  751       }
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

strong textObjects that are equal must have the same hash code within a running process

Please note that this does not imply the following common misconceptions:

Unequal objects must have different hash codes – WRONG!
Objects with the same hash code must be equal – WRONG!

enter image description here

The contract allows for unequal objects to share the same hash code, such as the “A“ and “µ” objects in the sketch above.

This is obvious because the number of possible distinct objects is usually bigger than the number of possible hash codes (2^32).

Sandeep Roniyaar
  • 204
  • 1
  • 8
  • 26