码迷,mamicode.com
首页 > 编程语言 > 详细

java中的equals()方法

时间:2015-08-01 20:29:27      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

大家都知道,在Java中,对于对象的比较,如果用“==”比较的是对象的引用,而equals才是比较的对象的内容。

 

一般我们在设计一个类时,需要重写父类的equals方法,在重写这个方法时,需要按照以下几个规则设计:

1、自反性:对任意引用值X,x.equals(x)的返回值一定为true.
2、对称性:对于任何引用值x,y,当且仅当y.equals(x)返回值为true时,x.equals(y)的返回值一定为true;
3、传递性:如果x.equals(y)=true, y.equals(z)=true,则x.equals(z)=true
4、一致性:如果参与比较的对象没任何改变,则对象比较的结果也不应该有任何改变
5、非空性:任何非空的引用值X,x.equals(null)的返回值一定为false

 

例如:

Java代码  技术分享
  1. public class People {  
  2.     private String firstName;  
  3.   
  4.     private String lastName;  
  5.   
  6.     private int age;  
  7.   
  8.     public String getFirstName() {  
  9.         return firstName;  
  10.     }  
  11.   
  12.     public void setFirstName(String firstName) {  
  13.         this.firstName = firstName;  
  14.     }  
  15.   
  16.     public String getLastName() {  
  17.         return lastName;  
  18.     }  
  19.   
  20.     public void setLastName(String lastName) {  
  21.         this.lastName = lastName;  
  22.     }  
  23.   
  24.     public int getAge() {  
  25.         return age;  
  26.     }  
  27.   
  28.     public void setAge(int age) {  
  29.         this.age = age;  
  30.     }  
  31.   
  32.     @Override  
  33.     public boolean equals(Object obj) {  
  34.         if (this == obj) return true;  
  35.         if (obj == null) return false;  
  36.         if (getClass() != obj.getClass()) return false;  
  37.         People other = (People) obj;  
  38.         if (age != other.age) return false;  
  39.         if (firstName == null) {  
  40.             if (other.firstName != null) return false;  
  41.         } else if (!firstName.equals(other.firstName)) return false;  
  42.         if (lastName == null) {  
  43.             if (other.lastName != null) return false;  
  44.         } else if (!lastName.equals(other.lastName)) return false;  
  45.         return true;  
  46.     }  
  47. }  

 

在这个例子中,我们规定一个人,如果姓、名和年龄相同,则就是同一个人。当然你也可以再增加其他属性,比如必须身份证号相同,才能判定为同一个人,则你可以在equals方法中增加对身份证号的判断!

java中的equals()方法

标签:

原文地址:http://www.cnblogs.com/langren1992/p/4694518.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!