StringBuffer equals方法是否比较内容? [英] Does the StringBuffer equals method compare content?

查看:135
本文介绍了StringBuffer equals方法是否比较内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

比较StringBuffer内容是否等于





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"?

推荐答案

StringBuffer 不会覆盖 Object.equals 方法,因此它不执行字符串比较。相反,它正在执行直接的对象比较。您的条件也可能是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.

请参见 http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer。 html

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

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆