Java字符串与字符串缓冲区
我在Java代码中有以下几行代码Java字符串与字符串缓冲区,java,string,stringbuffer,Java,String,Stringbuffer,我在Java代码中有以下几行代码 { String str1=new String("Vivek"); String str2=new String("Vivek"); StringBuffer str3=new StringBuffer("Vivek"); StringBuffer str4=new StringBuffer("Vivek"); System.out.println(str
{
String str1=new String("Vivek");
String str2=new String("Vivek");
StringBuffer str3=new StringBuffer("Vivek");
StringBuffer str4=new StringBuffer("Vivek");
System.out.println(str1.equals(str2));
System.out.println(str3.equals(str4));
}
现在我得到如下输出
True
False
我不明白为什么它为String对象打印true,为StringBuffer对象打印false?
它与对象的易变性有关吗?
StringBuffer
不重写equals
,因此调用超类对象的方法。
如果要比较内容,请使用toString
方法
System.out.println(str3.toString().equals(str4.toString()));
注意:由于Java 1.5StringBuffer
已被StringBuilder
取代,作为非线程替代方案StringBuffer
不会覆盖equals
,因此调用超类对象的方法。
如果要比较内容,请使用toString
方法
System.out.println(str3.toString().equals(str4.toString()));
注意:由于Java 1.5StringBuffer
已被StringBuilder
取代,成为一种非线程替代方案,因为类String
中的equals
被重写以比较内容,而类StringBuffer
中的equals
仍然是从类对象继承的比较地址
请参阅javadoc,您将了解更多
在字符串中,等于:
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.
Overrides: equals(...) in Object
Parameters:
anObject The object to compare this String against
Returns:
true if the given object represents a String equivalent to this string, false otherwise
See Also:
compareTo(String)
equalsIgnoreCase(String)
您可以使用:
str3.toString().equals(str4);
因为类String
中的equals
已被重写以比较内容,而类StringBuffer
中的equals
仍继承自比较地址的类对象
请参阅javadoc,您将了解更多
在字符串中,等于:
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.
Overrides: equals(...) in Object
Parameters:
anObject The object to compare this String against
Returns:
true if the given object represents a String equivalent to this string, false otherwise
See Also:
compareTo(String)
equalsIgnoreCase(String)
您可以使用:
str3.toString().equals(str4);
你是个魔术师!这无法编译。您的意思是StringBuffer str3=新的StringBuffer(“Vivek”)代码>?@ZouZou经过一个小的编辑:StringBuffer
类并不覆盖equals。由于您创建了两个全新的实例,它将返回false。StringBuffer
不会覆盖Object
中的equals
方法。equals(str4)
等同于Object.equals(Object)
您是魔术师!这无法编译。您的意思是StringBuffer str3=新的StringBuffer(“Vivek”)代码>?@ZouZou经过一个小的编辑:StringBuffer
类并不覆盖equals。由于您创建了两个全新的实例,它将返回false。StringBuffer
不会覆盖Object
中的equals
方法。equals(str4)
等同于Object.equals(Object)
,换句话说,它们不是为进行比较而设计的。换句话说,它们不是为了进行比较而设计的。是的…现在知道了…重点是String类重写了对象类中的Equalas方法,StringBuffer没有…是的…现在知道了…重点是String类重写了对象类中的Equalas方法,StringBuffer没有。。。