用String的equals方法比较一个StringBuffer的内容是否相等?

expeditioner 2007-05-18 01:35:29
如下代码中str 与 buffer中的内容都是Java,为什么却输出Both are not equal.

String str = "Java";
StringBuffer buffer = new StringBuffer(str);
if(str.equals(buffer)){
System.out.println("Both are equal");
}else{
System.out.println("Both are not equal");
}
...全文
548 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xingxiaoshuai 2011-01-11
  • 打赏
  • 举报
回复
你查查API就会发现,equals方法是属于类String的,而不属于类StringBuffer。

因此equals方法就只能操作String类型的对象,而不能操作StringBuffer类型的对象。

所以str.equals(buffer)的返回值应该是false。
yy80680169 2007-05-18
  • 打赏
  • 举报
回复
不是同一种对象 肯定是false
kevinliuu 2007-05-18
  • 打赏
  • 举报
回复
一个String ,一个StringBuffer,你比个啥啊

str.equals(buffer.toString()) 肯定返回true
flyforlove 2007-05-18
  • 打赏
  • 举报
回复

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) { //注意这儿
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}

62,614

社区成员

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

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