一个重写equals()和hashCode()方法的例子

来源:互联网 发布:网络歌手排行榜2008 编辑:程序博客网 时间:2024/05/21 23:33

下面是一个根据业务键实现equals()与hashCode()的例子。实际中需要根据实际的需求,决定如何利用相关的业务键来组合以重写这两个方法。

  

Java代码  收藏代码
  1. public class Cat   
  2. {  
  3.     private String name;  
  4.     private String birthday;  
  5.   
  6.     public Cat()  
  7.     {  
  8.     }  
  9.   
  10.     public void setName(String name)  
  11.     {  
  12.         this.name = name;  
  13.     }  
  14.   
  15.     public String getName()  
  16.     {  
  17.         return name;  
  18.     }  
  19.   
  20.     public void setBirthday(String birthday)  
  21.     {  
  22.         this.birthday = birthday;  
  23.     }  
  24.   
  25.     public String getBirthday()  
  26.     {  
  27.         return birthday;  
  28.     }  
  29.   
  30.        //重写equals方法  
  31.     public boolean equals(Object other)  
  32.     {  
  33.         if(this == other)  
  34.         {  
  35.             //如果引用地址相同,即引用的是同一个对象,就返回true  
  36.             return true;  
  37.         }  
  38.   
  39.             //如果other不是Cat类的实例,返回false  
  40.         if(!(other instanceOf Cat))  
  41.         {  
  42.             return false;  
  43.         }  
  44.   
  45.         final Cat cat = (Cat)other;  
  46.             //name值不同,返回false  
  47.         if(!getName().equals(cat.getName())  
  48.             return false;  
  49.             //birthday值不同,返回false  
  50.         if(!getBirthday().equals(cat.getBirthday()))  
  51.             return false;  
  52.   
  53.         return true;  
  54.     }  
  55.   
  56.        //重写hashCode()方法  
  57.     public int hashCode()  
  58.     {  
  59.         int result = getName().hashCode();  
  60.         result = 29 * result + getBirthday().hashCode();  
  61.         return result;  
  62.     }  
  63. }  

   重写父类方法的原则:可以重写方法的实现内容,成员的存取权限(只能扩大,不能缩小),或是成员的返回值类型(但此时子类的返回值类型必须是父类返回值类型的子类型)。


原创粉丝点击