平时经常会遇到判断两个东西是否相等,一般字符串的话我都是用str.equals('str1')数字之类的就用 if ( a == 10) 但是这两个究竟有什么区别呢?
《JAVA编程思想》第四版中的原话
如果想比较两个对象的实际内容是否相同,必须使用所有对象都使用的特殊方法equals()。但这个方法不适用于“基本类型”,基本类型直接用==
equals()这个方法被定义在Object这个基类中,也就是说每个类都有这个方法,因为JAVA中每个类都会继承这个基类。看看帮助文档中怎么解释
-
public boolean equals(Object obj)
Indicates whether some other object is "equal to" this one.The
equals
method implements an equivalence relation on non-null object references:- It is reflexive: for any non-null reference value
x
,x.equals(x)
should returntrue
. - It is symmetric: for any non-null reference values
x
andy
,x.equals(y)
should returntrue
if and only ify.equals(x)
returnstrue
. - It is transitive: for any non-null reference values
x
,y
, andz
, ifx.equals(y)
returnstrue
andy.equals(z)
returnstrue
, thenx.equals(z)
should returntrue
. - It is consistent: for any non-null reference values
x
andy
, multiple invocations ofx.equals(y)
consistently returntrue
or consistently returnfalse
, provided no information used inequals
comparisons on the objects is modified. - For any non-null reference value
x
,x.equals(null)
should returnfalse
.
The
equals
method for classObject
implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference valuesx
andy
, this method returnstrue
if and only ifx
andy
refer to the same object (x == y
has the valuetrue
).Note that it is generally necessary to override the
hashCode
method whenever this method is overridden, so as to maintain the general contract for thehashCode
method, which states that equal objects must have equal hash codes.-
Parameters:
-
obj
- the reference object with which to compare.
Returns:
-
true
if this object is the same as the obj argument;false
otherwise.
See Also:
-
hashCode()
,HashMap
- It is reflexive: for any non-null reference value