2012-06-20 79 views

回答

31

因为StringBuffer是可变的,它的主要用途是用于构建字符串。如果您想比较内容,请致电StringBuffer#toString()并比较返回的值。

对于可变对象覆盖hashCode()通常不会有用,因为修改用作HashMap中的键的对象可能会导致存储的值“丢失”。

+0

Mutable是什么意思? – Saravanan

+4

做一些研究,如果你不明白的基本原则:http://stackoverflow.com/questions/3554192/what-is-a-mutable-class-in-oop –

+1

尽我所能,我不同意你的发言_重写hashCode()用于可变对象通常不会很有用... _ – Shahzeb

5

实际上,这一切背后都取决于散列码值。为了理解这个概念允许以一个例子:

String str1 = new String("sunil"); 
String str2 = new String("sunil"); 

HashMap hm = new HashMap() 
hm.put(str1,"hello"); 
hm.put(str2,"bye"); 

最终HM:

hm = { sunil=bye } 

在上面的代码中,str1和STR2是两个不同的字符串对象。它应该添加到HashMap中?答案是NO。因为在将值插入/放入HashMap之前,它会在内部检查并比较hashCode值str1,str2。由于String类覆盖了equals()和hashcode()方法,所以两者都会重新调用相同的hascode值。所以在执行hm.put(str2,"bye");时,第一个键会被新值覆盖。现在试试这个:

StringBuilder sb1 = new StringBuilder("sunil"); 
StringBuilder sb2 = new StringBuilder("sunil"); 

HashMap hm = new HashMap() 
hm.put(sb1,"hello");//sb1 and sb2 will return different HashCode 
hm.put(sb2,"bye");// StringBuffer/StringBuilder does not override hashCode/equals methods 

最终HM:

{sunil=hello, sunil=bye} 

两个值将在HashMap中添加,因为SB1和SB2都返回不同的散列码。 StringBuilder/StringBuffer不会覆盖equals()和hashCode()方法。

Sun Microsystem希望程序员允许在Hashtable或任何其他Hash Collections like(HashSet,HashMap ...)中添加2种不同的String类型值,这就是hashCode()和equals()在StringBuffer中没有被有意覆盖的原因,StringBuilder类。

+0

'Sun Microsystem希望程序员允许在Hashtable中添加2种不同的String类型的值......'这不是真的,['Hashtable']的javadocs(https:// docs。 oracle.com/javase/8/docs/api/java/util/Hashtable.html)和['Map'](https://docs.oracle。com/javase/8/docs/api/java/util/Map.html)积极劝阻使用带有“equals/hashcode”合约的对象作为键。将'StringBuilder'对象存储在映射中并不有用,因为除非拥有原始对象,否则无法通过键获取值。 –

-2

因为StringBuffer是mutable。用示例试试:)

package test; 

import java.util.HashMap; 

public class CheckHashcodeEquals { 

    public static void main(String[] args) { 

     /* 
     * String class override equals() and hashcode() method thats way 
     * override value of HashMap 
     */ 
     String s1 = new String("Arya"); 
     String s2 = new String("Arya"); 
     HashMap hm = new HashMap<>(); 
     hm.put(s1, "A1"); 
     hm.put(s2, "A2"); 
     System.out.println(hm); /* Output: {Arya=A2} */ 

     /* 
     * String class does not override equals() and hashcode() method thats 
     * way insert duplicate value 
     */ 
     StringBuffer sb1 = new StringBuffer("Arya"); 
     StringBuffer sb2 = new StringBuffer("Arya"); 
     HashMap hm2 = new HashMap<>(); 
     hm2.put(sb1, "A1"); 
     hm2.put(sb2, "A2"); 
     System.out.println(hm2); /* Output: {Arya=A2, Arya=A1} */ 
    } 

} 
+0

这个例子演示'StringBuffer'不会覆盖'equals'和'hashcode',但不会显示原因。答案本身('因为StringBuffer是可变的)从早期的答案中复制而来。 –

相关问题