zoukankan      html  css  js  c++  java
  • java中的equals()方法

    大家都知道,在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方法中增加对身份证号的判断!

  • 相关阅读:
    使用js来执行全屏
    vue多个组件的过渡
    mac笔记本上的工具
    webpack优化技术参考
    VS Code 编译器的调试工具整理
    自定义滑块Vue组件
    Multi-level Multi-select plugin
    cucumber learning : http://www.cnblogs.com/puresoul/category/340832.html
    Opensuse enable sound and mic card
    Shell displays color output
  • 原文地址:https://www.cnblogs.com/langren1992/p/4694518.html
Copyright © 2011-2022 走看看