另外,值得指出的是,Java不充许操作符重写(Overwrite),所以对于任何类型的对象来说,==的意义是相同的。在这一点上,equals()就不同了,见下文解释。
2. equals() 1). 概述 equals()可以用来比较两个对象,基本类型比较无法使用equals()。
Java在Object类中提供了equals()的实现,由于Java的单根继承特性,你可以在任何类中调用equals()方法。另一方面,由于equals()可能被子类重写(overwrite),所以不同的类的equals()方法可能有所不同。当然,子类也不应该随意地实现equals()方法,Java为equals()方法规定了一些需要遵守的共同约定,这在JDK文档里面有很详细的描述,摘抄于下:
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 return true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false.
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.