Thinking in Java 4th学习笔记--Java中的双等号(==)比较操作符与equals()方法
双等号(==)比较操作符 用于比较两个对象的内存地址是否相等。
equals()方法 用于比较两个对象的内容是否一致。
public class Equivalence{
public static void main(String[] args){
Integer n1 = new Integer(22);
Integer n2 = new Integer(22);
System.out.println(n1 == n1);
System.out.println(n1 == n2);
System.out.println(n1 != n2);
}
}
输出结果:
说明:
while the contents of the objects are the same, the references are
not the same. The operators == and != compare object references, so the output is actually
“false” and then “true.” Naturally, this surprises people at first.
对象的内容相同,但对象的引用(句柄)却不同。 == 和 != 比较的是对象的引用(句柄)。
What if you want to compare the actual contents of an object for equivalence? You must use
the special method equals( ) that exists for all objects (not primitives, which work fine with
== and !=). Here’s how it’s used:
如果想比较对象的实际内容是否相等,该怎么办呢?这时就必须用 equals()方法了。
equals()方法对主类型不适用,主类型用== 和 != 进行比较。
public class EqualsMethod{
public static void main(String [] args){
Integer n1 = new Integer(33);
Integer n2 = new Integer(33);
System.out.println(n1==n2);
System.out.println(n1.equals(n2));
}
}
输出结果:
事情就这么完了?没呢。如果你创建了自己的类,再使用equals()方法时,会是什么结果呢?
class Value{
int i;
}
public class EqualsMethod2{
public static void main(String [] args){
Value v1 = new Value();
Value v2 = new Value();
v1.i = v1.i = 100;
System.out.println(v1.equals(v2));
}
}
输出结果:
说明:
things are confusing again: The result is false . This is because the default behavior of
equals( ) is to compare references. So unless you override equals( ) in your new class you
won’t get the desired behavior. Unfortunately, you won’t learn about overriding until the
Reusing Classes chapter and about the proper way to define equals( ) until the Containers
in Depth chapter, but being aware of the way equals( ) behaves might save you some grief in
the meantime.
Most of the Java library classes implement equals( ) so that it compares the contents of
objects instead of their references.
此时的结果又变回了false!这是由于equals()的默认行为是比较句柄。所以除非在自己的新类中改变了
equals(),否则不可能表现出我们希望的行为。不幸的是,要到第7章才会学习如何改变行为。但要注意
equals()的这种行为方式同时或许能够避免一些“灾难”性的事件。
大多数Java类库都实现了equals(),所以它实际比较的是对象的内容,而非它们的句柄
本文作者:@易枭寒