新人,关于StringBuilder的equals方法,求大神指点一下

小谢哥 2012-04-13 02:03:51
import java.io.*;
public class TestStringBuffer01
{
public static void main(String args[])throws IOException
{
BufferedReader buf;
String s1;
buf =new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入字符串:");
s1=buf.readLine();
StringBuffer sb1=new StringBuffer(s1);
StringBuffer sb2=sb1.reverse();
//System.out.println(sb1);
//System.out.println(sb2);
System.out.print("s1是否为回文:"+s1.equals(sb2.toString()));//这里的比较,sb2为什么要加toString啊?因为它是StringBuilder类型吗?
}
}
不是很懂哎!!!求指点......
...全文
189 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
小谢哥 2012-04-13
  • 打赏
  • 举报
回复
恩恩,学习了。。。现在初学java,以后还有很多不懂的需要请教哈。
古市轩 2012-04-13
  • 打赏
  • 举报
回复
查看API:equals方法的说明:
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
也就是说:将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。
StringBuilder与String类型都不同,比较的话肯定返回false,所以要先把StringBuilder.toString()转换为String类型比较才有意思!
小谢哥 2012-04-13
  • 打赏
  • 举报
回复
奥,懂了。谢谢
yizhizouxiaqu 2012-04-13
  • 打赏
  • 举报
回复
先要弄清楚s1为String类型,而sb2是StringBuilder类,首先两个类型就不同。你看一下String的equal方法定义,它会首先判断参数是否为String类型,如果不是String类型就直接返回错误。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧