A Set in java never allows duplicates, but it takes StringBuffer objects with the same argument. Why?

后端 未结 6 2066
失恋的感觉
失恋的感觉 2021-01-12 21:55
public static void main(String[] args) {
    HashSet set = new HashSet(); 
    set.add(new StringBuffer(\"abc\"));
    set.add(new StringBuffer(\"abc\")); 
    set.a         


        
6条回答
  •  情深已故
    2021-01-12 22:44

    StringBuffer does not override Object#equals() and Object#hashCode(), so identity of StringBuffer instances is based not on the contents of the buffer, but by the object's address in memory.*


    * That identity is based on an address in memory is not strictly required by the JLS, but is a consequence of a typical Object#hashCode() implementation. From the JavaDoc:

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)

提交回复
热议问题