==对于基本类型,比较的是他们的值是否相等,对于引用类型,比较的是内存中,他们是否都指向内存中同一个对象.
所有类都继承Object类的equals()方法,此方法默认的实现使用==比较,一些类重载了equals()方法,从而比较的是对象的内容.
We’ve seen that primitive types and reference types differ significantly in the way
they are assigned to variables, passed to methods, and copied. The types also differ
in the way they are compared for equality. When used with primitive values, the
equality operator (==) simply tests whether two values are identical (i.e., whether
they have exactly the same bits). With reference types, however, == compares refer‐
ences, not actual objects. In other words, == tests whether two references refer to the
same object; it does not test whether two objects have the same content.When working with reference types, there are two kinds of equality: equality of ref‐
erence and equality of object. It is important to distinguish between these two kinds
of equality. One way to do this is to use the word “identical” when talking about
equality of references and the word “equal” when talking about two distinct objects
that have the same content. To test two nonidentical objects for equality, pass one of
them to the equals() method of the other:All objects inherit an equals() method (from Object), but the default implementa‐
tion simply uses == to test for identity of references, not equality of content. A class
that wants to allow objects to be compared for equality can define its own version of
the equals() method. Our Point class does not do this, but the String class does,
as indicated in the code example. You can call the equals() method on an array, but
it is the same as using the == operator, because arrays always inherit the default
equals() method that compares references rather than array content. You can com‐
pare arrays for equality with the convenience method java.util.Arrays.equals().