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

后端 未结 6 1979
失恋的感觉
失恋的感觉 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:41

    Did it occur to you to see the equals() method (or the lack of it) in the StringBuffer? There lies the answer for you.

    A Set or for that matter any hash based collection depends on the contract exposed by the equals() and hashcode() method on the Object for their behavior characteristic.

    In your case since StringBuffer doesn't override these methods each StringBuffer instance that you create is different i.e new StringBuffer("abc") == new StringBuffer("abc") will return false.

    I am curious as to why would someone add StringBuffer to a set.

提交回复
热议问题