本文介绍了将StringBuffer内容与equals进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
StringBuffer sb1 = new StringBuffer("Java");
StringBuffer sb2 = new StringBuffer("Java");
System.out.println(sb1 == sb2);
System.out.println(sb1.equals(sb2));
这两个都返回false。怎么可能?
Here both are returning false. How is it possible?
推荐答案
<$ c的等于
方法$ c> StringBuffer 未从 Object
覆盖,因此它只是引用相等,即与使用 =相同=
。我怀疑这样做的原因是 StringBuffer
是可修改的,并且覆盖等于
对于类似于值的类来说非常有用你可能想用作键(虽然列表也有一个被覆盖的等于
而 StringBuffer
是一种列表,所以这有点不一致。)
The equals
method of StringBuffer
is not overridden from Object
, so it is just reference equality, i.e., the same as using ==
. I suspect the reason for this is that StringBuffer
is modifiable, and overriding equals
is mostly useful for value-like classes that you might want to use as keys (though lists also have an overridden equals
and StringBuffer
is kind of a list, so this is a bit inconsistent).
这篇关于将StringBuffer内容与equals进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!