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");
}
为什么该代码打印“False”?
Possible Duplicate:
Comparing StringBuffer content with 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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
StringBuffer 不会覆盖 Object.equals 方法,因此它不执行字符串比较。相反,它执行直接对象比较。您的条件也可以是 if(s1==s2)。如果您想比较字符串,您需要首先将缓冲区转换为字符串。
请参阅 http://java.sun.com/ j2se/1.5.0/docs/api/java/lang/StringBuffer.html
编辑:我假设我们处于 Java 世界中。
ps 如果您处于单线程环境中,或者您的缓冲区被隔离到单个线程,那么您确实应该使用 StringBuilder 而不是 StringBuffer.
StringBuffer does not override the Object.equals method, 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.
See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html
Edit: I'm assuming we're in a java world.
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 StringBuilder instead of a StringBuffer.
StringBuffer equals 不会被重写来检查内容。它使用默认的“浅等于”来比较从 java.lang.Object 继承的引用。
StringBuffer equals isn't overridden to check content. It's using the default "shallow equals" that compares references it inherits from java.lang.Object.