How to use the Mutable key in the hashamp working in this example?

  HashMap hm = new HashMap();
  StringBuilder sb = new StringBuilder("test");
  hm.put(sb, "second");
  // above code gets hacode for sb and places it corresponding bucket

  sb.append("123");// with appending of "123", sb hascode will change

  System.out.println("element is is" + hm.get(sb));// print "second"

Now hm.get (sb) should look for the key in the bucket according to the new hash code. therefore, it should not be this bucket and should turn out to be zero. So why is getting it "second"?

+4
source share
2 answers

The class StringBuilderdoes not overridehashCode , so it inherits a method hashCodefrom Object> . Therefore, the content StringBuilder'does not affect the hash code, and even when you change its content, HashMapit can still find it StringBuilder.

+7
source

, StringBuilder hashCode(), hashCode() Object, . , , .

, , hashCode

@Override
public int hashCode() {
    return this.toString().hashCode();
}

equals().

+1

Source: https://habr.com/ru/post/1529862/


All Articles