Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <ol> <li><p>Immutable keys cannot change. Consequently, the hashcode which is computed at the time of insertion cannot change. So when you try to <em>get</em> an element from the map, the hashcode of the object to get is computed against known hashcodes. Had your key changed from outside(it was mutable), the new key's hashcode would be different from the one which you inserted.</p></li> <li><p>Let's see an example. for(<code>2</code> and <code>4</code>)</p> <pre><code>public class RandomPair { int p; int q; public RandomPair(int p, int q) { this.p = p; this.q = q; } @Override public int hashCode() { return 31 * p + q; } @Override public boolean equals(Object obj) { if (!(obj instanceof RandomPair)) { return false; } if (obj == this) { return true; } RandomPair other = (RandomPair) obj; if (p != other.p) return false; if (q != other.q) return false; return true; } public static void main(String[] args) { RandomPair pair = new RandomPair(10, 10); Map&lt;RandomPair, Integer&gt; map = new HashMap&lt;RandomPair, Integer&gt;(); map.put(pair, 1); System.out.println(map.get(pair)); //returns 1 //someone somewhere just changed the value of pair pair.p = 20; //the object was the same, someone somewhere just changed value of pair and now you can't //find it in the map System.out.println(map.get(pair)); //had you made p and q final, this sort of modification wouldn't be possible //Strings are immutable and thus prevent this modification } } </code></pre></li> <li><p>Since strings are immutable, the hashcode value once computed can be reused again. The hashcode is lazily computed. ie on the first call to hashcode and then the value of hashcode is cached.</p></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload