本文介绍了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?

Why does that code print "False"?

推荐答案

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

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.

请参见

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

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

ps如果您在单线程环境中,或者您的缓冲区被隔离到单个线程中,那么您实际上应该使用而不是。

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方法是否比较内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 22:17