将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> 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).