I was playing around with Classname.class and Classname.class.toString() and found something unusual.
.class seems to equate to .class when run on the same Class. Although .class.toString() does not equate to the .class.toString() on the same class. Why would this be.
Please see my code below
public class HelloWorld{
public static void main(String []args){
if(String.class.toString() == String.class.toString())
System.out.println("toString(): Yes they are the same");
else
System.out.println("toString(): They are not the same ?");
System.out.println("=============================");
if(String.class == String.class)
System.out.println(".class: Yes they are the same");
else
System.out.println(".class: They are not the same");
}
}
Output:
sh-4.3# javac HelloWorld.java
sh-4.3# java -Xmx128M -Xms16M HelloWorld
toString(): They are not the same ?
=============================
.class: Yes they are the same
答案 0 :(得分:4)
Because you don't use == operator to compare strings. Use .equals() method instead.
答案 1 :(得分:2)
Why do you expect that one toString()
invocation would return the exact same object as a second invocation? Neither Object.toString()
nor Class.toString()
specifies in their Javadoc API documentation that the same String
object will be returned in successive invocations.
Without a reason to do otherwise, one must assume the default contract that String
instances must be compared with equals()
.
答案 2 :(得分:1)
在这里,您要比较引用,而不是字符串内容,并且引用不等于。
String.class.toString() == String.class.toString()
您必须与equals进行比较:
String.class.toString().equals(String.class.toString())
或者您可以与字符串的高级功能进行比较,如下所示:
String.class.toString().intern() == String.class.toString().intern()