Comparison of equals in Java, a small pitfall, and javaequals

Source: Internet
Author: User

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 notNullAnd the object contains the sameIntValueIntegerObject, the result isTrue.


String equals

Compare this object with the specified object. If and only if the parameter is notNullAnd 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.