Comparison of equals in Java, a small pitfall, and javaequals
In recent work, we often need to compare the values of two objects. There is a problem that is often encountered in the following two cases.
Public static void main (String [] args ){
Integer a = 11;
Object B =;
System. out. println (B. equals ("11"); // false
String c = "11 ";
Object d = c;
System. out. println (d. equals ("11"); // true
}
View the JDK documentation in Chinese:
Integer equals
Compare this object with the specified object. If and only if the parameter is notNull
And the object contains the sameInt
ValueInteger
Object, the result isTrue
.
String equals
Compare this object with the specified object. If and only if the parameter is notNull
And is a string object that contains the same String value as this object, the result isTrue
.
Both String and Integer overload the equals method of the Object. Therefore, the comparison between the two objects must be of the same type.
This type should be "actual type". The actual type of Object d is "String". Therefore, the equals method of String is called.
Polymorphism ~
First: http://fansunion.cn/article/detail/536.html