java StringBuffer equals 方法是否比较内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2192032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:57:36  来源:igfitidea点击:

Does the StringBuffer equals method compare content?

javastringequalsstringbuffer

提问by rocker

Possible Duplicate:
Comparing StringBuffer content with equals

可能的重复:
将 StringBuffer 内容与 equals 进行比较

StringBuffer s1= new StringBuffer("Test");
StringBuffer s2 = new StringBuffer("Test");
if(s1.equals(s2)) {
  System.out.println("True");
} else {
  System.out.println("False");
}

Why does that code print "False"?

为什么该代码打印“假”?

回答by Michael Krauklis

StringBufferdoes not override the Object.equalsmethod, so it is not performing a string comparison. Instead it is performing a direct object comparison. Your conditional may as well be if(s1==s2). If you want to compare the strings you'll need to turn the buffers into strings first.

StringBuffer不会覆盖Object.equals方法,因此它不会执行字符串比较。相反,它正在执行直接对象比较。您的条件也可能是 if(s1==s2)。如果要比较字符串,则需要先将缓冲区转换为字符串。

See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html

Edit: I'm assuming we're in a java world.

编辑:我假设我们在 Java 世界中。

p.s. If you're in a single-threaded environment, or your buffers are isolated to a single thread, you should really be using a StringBuilderinstead of a StringBuffer.

ps 如果您处于单线程环境中,或者您的缓冲区与单个线程隔离,那么您确实应该使用StringBuilder而不是StringBuffer

回答by duffymo

StringBuffer equals isn't overridden to check content. It's using the default "shallow equals" that compares references it inherits from java.lang.Object.

StringBuffer equals 不会被覆盖以检查内容。它使用默认的“浅等于”来比较它从 java.lang.Object 继承的引用。