JAVA中equals()的用法

需要覆盖equals:如果类具有自己特有的“逻辑相等”概念,而且超类还没有覆盖equals以实现期望的行为,这时我们就需要覆盖equals方法。 

不需要覆盖equals:用实例受控确保“每个值至多只存在一个对象”的类。枚举类型就属于这种类。对于这样的类而言,逻辑相同与对象等同是一回事。 

 

Object类中的equals方法用于检测一个对象是否等于另一个对象。在Object类中,这个方法判断两个对象是否具有相同的引用,如果两个对象具有相同的引用,它们一定是相等的。从这点上看,将其作为默认操作也是合乎情理的。然而,对于多数类类说,这种判断并没有什么意义,例如,采用这种方式比较两个PrintStream是否相等就完全没有意义。然而,经常需要检测两个对象状态的相等性,如果两个对象的状态相等,就认为这两个对象是相等的。所以一般在自定义类中都要重写equals比较。

下面给出编写一个完美equals()方法的建议:

1)显式参数命名为otherObject,稍后需要将转换成一个叫other的变量

2)检测this与otherObject是否引用同一个对象:

if(this==otherObject) return true;

这条语句只是一个优化。实际上,这是一种经常采用的形式。因为计算这个等式要比一个一个地比较类中的域所付出的代价小的多。

3)检测otherObject是否为null,如果为null,返回false。这项检测是很必要的。

if(otherObject==null) return false;

4)比较this和otherObject是否属于同一个类,如果equals的语义在每个子类中有所改变,就使用getClass()检测,它将自己作为目标类

if(getClass()!=otherObject.getClass()) return false;

如果所有的子类都拥有同一的语义,就使用instanceof检测

if(!(otherObject instanceof ClassName)) return false;

5)将otherObject转换为相应类型的变量:

ClassName other=(ClassName)otherObject;

6)现在开始对所有需要比较的域进行比较。使用==比较基本类型域,使用equals比较对象域。如果所有域都匹配,就返回true,否则返回false;

return field1==other.field1&&field2.equals(other.field2)

如果在子类中重新定义equals,就要在其中包含调用super.equals(other)。如果检测失败,就不可能相等。如果超类中的域相等,就比较子类中的实例域。

对于数组类型的域,可以使用静态的Arrays.equals方法检测相应的元素是否相等。

 

每个覆盖了equals方法的类中,也必须覆盖hashCode方法。 
如果不这样的话,就会违反Object.hashCode的通用约定,从而导致该类无法结合所有基于散列的集合一起正常运作,这样的集合包括HashMap、HashSet和Hashtable。

在引用程序的执行期间,只要对象的equals方法的比较操作所用到的信息没有被修改,那么对这同一个对象调用多次,hashCode方法都必须始终如一的返回同一个整数。在一个应用程序的多次执行过程中,每次执行所返回的整数可以不一致。 
如果连个对象根绝equals方法比较是相等的,那么调用这两个对象中任意一个对象的hashCode方法都必须产生同样的整数结果。 

 

来看几个字符串比较例子:

 

[java]  view plain  copy
 
  print ?
  1. String a = "abc";  
  2. String b = "abc";  
  3. String c = new String("abc");  
  4. String d = new String("abc");  
  5. System.out.println(a == b); // true 因为JAVA中字符串常量是共享的,只有一个拷贝  
  6. System.out.println(a == c); // false a和c属于2个不同的对象  
  7. System.out.println(a.equals(c)); // true 由于String对象的equals方法比较的是对象中的值,所以返回true。(和Object的equals方法不同)  
  8. System.out.println(c==d); // false c和d虽然对象内的值相同,但属于2个不同的对象,所以不相等  
  9. System.out.println(c.equals(d)); // true   

简单的说,当比较字符串常量时,等于和equals返回的结果一样,当想比较字符串对象的值时用equals。

 

看一个equals的使用例子:

 

[java]  view plain  copy
 
  print ?
  1. package chapter05.EqualsTest;  
  2.   
  3. import java.util.*;  
  4.   
  5. public class EqualsTest {  
  6.     public static void main(String[] args) {  
  7.         Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);  
  8.         Employee alice2 = alice1; // reference the same object  
  9.         Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);  
  10.         Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);  
  11.   
  12.         System.out.println("alice1 == alice2: " + (alice1 == alice2));  
  13.   
  14.         System.out.println("alice1 == alice3: " + (alice1 == alice3));  
  15.   
  16.         System.out.println("alice1.equals(alice3): " + (alice1.equals(alice3)));  
  17.   
  18.         System.out.println("alice1.equals(bob): " + (alice1.equals(bob)));  
  19.   
  20.         System.out.println(bob.toString());  
  21.     }  
  22. }  
  23.   
  24. class Employee {  
  25.     public Employee(String n, double s, int year, int month, int day) {  
  26.         name = n;  
  27.         salary = s;  
  28.         GregorianCalendar calendar = new GregorianCalendar(year, month, day);  
  29.         hireDay = calendar.getTime();  
  30.     }  
  31.   
  32.     public String getName() {  
  33.         return name;  
  34.     }  
  35.   
  36.     public double getSalary() {  
  37.         return salary;  
  38.     }  
  39.   
  40.     public Date getHireDay() {  
  41.         return hireDay;  
  42.     }  
  43.   
  44.     public void raiseSalary(double byPercent) {  
  45.         double raise = salary * byPercent / 100;  
  46.         salary += raise;  
  47.     }  
  48.   
  49.     @Override  
  50.     public boolean equals(Object otherObject) {  
  51.         // a quick test to see if the objects are identical  
  52.         if (this == otherObject)  
  53.             return true;  
  54.   
  55.         // must return false if the explicit parameter is null  
  56.         if (otherObject == null)  
  57.             return false;  
  58.   
  59.         // if the classed don't match,they can't be equal  
  60.         if (getClass() != otherObject.getClass())  
  61.             return false;  
  62.   
  63.         // now we know otherObject is a non-null Employee  
  64.         Employee other = (Employee) otherObject;  
  65.   
  66.         // test whether the fields hava identical values  
  67.         return name.equals(other.name) && salary == other.salary  
  68.                 && hireDay.equals(other.hireDay);  
  69.   
  70.     }  
  71.   
  72.     @Override  
  73.     public int hashCode() {  
  74.         return 7 * name.hashCode() + 11 * new Double(salary).hashCode() + 13  
  75.                 * hireDay.hashCode();  
  76.     }  
  77.   
  78.     @Override  
  79.     public String toString() {  
  80.         return getClass().getName() + "[name=" + name + ",salary=" + salary  
  81.                 + ",hireDay=" + hireDay + "]";  
  82.     }  
  83.   
  84.     private String name;  
  85.     private double salary;  
  86.     private Date hireDay;  
  87. }  
  88.   
  89. class Manager extends Employee {  
  90.     public Manager(String n, double s, int year, int month, int day) {  
  91.         super(n, s, year, month, day);  
  92.         bouns = 0;  
  93.     }  
  94.   
  95.     @Override  
  96.     public double getSalary() {  
  97.         double baseSalary = super.getSalary();  
  98.         return baseSalary + bouns;  
  99.     }  
  100.   
  101.     public void setBouns(double b) {  
  102.         bouns = b;  
  103.     }  
  104.   
  105.     @Override  
  106.     public boolean equals(Object otherObject) {  
  107.         if (!super.equals(otherObject))  
  108.             return false;  
  109.         Manager other = (Manager) otherObject;  
  110.         // super equals checked that this and other belong to the same class  
  111.         return bouns == other.bouns;  
  112.     }  
  113.   
  114.     @Override  
  115.     public int hashCode() {  
  116.         return super.hashCode() + 17 * new Double(bouns).hashCode();  
  117.     }  
  118.   
  119.     @Override  
  120.     public String toString() {  
  121.         return super.toString() + "[bouns=" + bouns + "]";  
  122.     }  
  123.   
  124.     private double bouns;  
  125. }  

猜你喜欢

转载自windpoplar.iteye.com/blog/2315969
今日推荐