Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how using Mutable key in 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 search the key in the bucket as per new hashcode. so it should not get any object under that bucket and should get null . So why its getting "second"?

like image 483
M Sach Avatar asked Feb 13 '23 15:02

M Sach


2 Answers

The StringBuilder class does not override hashCode, so it inherits the hashCode method from Object. Therefore, the StringBuilder's contents do not affect the hash code, and even when you change its contents, the HashMap is still able to find the StringBuilder.

like image 162
rgettman Avatar answered Feb 24 '23 14:02

rgettman


By default it looks like StringBuilder doesn't use its contents as part of its hashCode(), it just inherits the default hashCode() from Object which uses the memory address as its seed. So the memory address hasn't changed, thus the key still works.

If you wanted the behavior you expected, override the hashCode method to return

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

and don't forget to override equals() as well.

like image 29
Magnus Avatar answered Feb 24 '23 14:02

Magnus