JAVA中equals()与==的区别详解

在进行判断操作时,常常会用到==或者equals()进行等价判断,那么两者究竟有什么区别呢,下面整理一下个人理解。

  • 简单介绍:
    ==是一种引用相等性比较符,判断引用到堆上同一个对象的两个引用是相等的。要比较两个基本类型是否相等,一般使用==。示意图:
    ==示意图
    equals()方法是一种对象相等性比较方法,判断堆上的两个不同对象在意义上是相同的。如果一个变量指向的数据为对象类型,如java的包装类(String等),则一般使用equals()进行比较。示意图:
    equals()示意图

  • 例:

    1 int a = 10;
    2 int b = 10;
    3 //那么a == b将会返回true。  
    4 
    5 String a = new String("aa");
    6 String b = new String("aa");
    7 //那么a == b将会返回false,a.equals(b)返回true。
  • StackOverFlow中对equals()的使用提出了几个需要注意的地方:

    equals will only compare what it is written to compare, no more, no less.

    • equals方法只会实现方法中所写的比较逻辑。

    if a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.

    • 如果没有重写equals(),默认使用该类最近且重写了equals()的父类方法。需通过api查阅该父类equals()的实现逻辑,如果不符合你想要实现的,要重写equals()和hashCode()两个方法。

    If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you’re left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.

    • 如果没有父类重写equals(),则默认使用Objec类的equals()。通过API可知Object类的equals()实现逻辑与==一样。

    Always remember to override hashCode if you override equals so as not to “break the contract”. As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods shows that they are equivalent. The converse is not necessarily true.

    • 重写equals()的同时需重写hashCode(),查阅API可知,如果equals()返回true时,两个对象的hashCode也应该相等,否则不能保证结果完全正确。
posted @ 2015-06-03 17:25  honoka  阅读(...)  评论(...编辑  收藏