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"?
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.
StringBuilder
hashCode
Object
StringBuilder'
HashMap
, StringBuilder hashCode(), hashCode() Object, . , , .
, , hashCode
@Override public int hashCode() { return this.toString().hashCode(); }
equals().
Source: https://habr.com/ru/post/1529862/More articles:Сохранение капель с конечной точкой Google - javaHow to create a component diagram from code, Visual Studio 2012 Ultimate - visual-studio-2012How do I represent options (types of sums) in JSON? - jsonMaven pom.xml error in eclipse - eclipseHow to change the text of the delivery address and invoicing address on the page received when ordering woocommerce? - phpExcel VBA connects to a remote Oracle database using InstantClient - sqlJava uses mouseMove with multiple monitors - javaOrientDB Time Series Data - graphWhat is the difference between json.dumps and str ()? - pythonJava gets mouse location in a multi-monitor environment - javaAll Articles