Discuss / Java / 覆写equals()方法

覆写equals()方法

Topic source

#1 Created at ... [Delete] [Delete and Lock User]
import java.util.*;
public class Main {
    public static void main(String[] args) {
    List<Person> list =new ArrayList<Person>();        
    list.add(new Person("Xiao", "Ming", 18));        
    list.add(new Person("Xiao", "Hong", 25));        
    list.add(new Person("Bob", "Smith", 20));                     
    boolean exist = list.contains(new Person("Bob", "Smith", 20));        
    System.out.println(exist ? "测试成功!" : "测试失败!");    }
}

class Person {
    String firstName;    
    String lastName;    
    int age;    
    public Person(String firstName, String lastName, int age) {
    this.firstName = firstName;        
    this.lastName = lastName;        
    this.age = age;    }

public boolean equals(Object o){
     if(o instanceof Person){
             Person p=(Person) o;            
             return Objects.equals(p.firstName,this.firstName)&& p.age==this.age && Objects.equals(p.lastName,this.lastName);        }
      return false;    }
}

rm -rf *

#2 Created at ... [Delete] [Delete and Lock User]

这个是idea自动生成的,不需要instanceof判断

@Overridepublic boolean equals(Object o) {    if (this == o) return true;    if (o == null || getClass() != o.getClass()) return false;    Person person = (Person) o;    return age == person.age && Objects.equals(name, person.name);}@Overridepublic int hashCode() {    return Objects.hash(name, age);}

  • 1

Reply