Java重写hashCode()和equals(Object obj)方法进行对象的判断

Student类:重写hashcode()方法和equals()方法

ackage com.lx.dome;

import java.io.Serializable;

public class Student implements Serializable{
/**
     * 
     */
    private static final long serialVersionUID = 1L;
private Integer stuId;
private Integer stuAge;
private String stuName;

public Integer getStuId() {
    return stuId;
}
public void setStuId(Integer stuId) {
    this.stuId = stuId;
}
public Integer getStuAge() {
    return stuAge;
}
public void setStuAge(Integer stuAge) {
    this.stuAge = stuAge;
}
public String getStuName() {
    return stuName;
}
public void setStuName(String stuName) {
    this.stuName = stuName;
}

@Override
public String toString() {
    return "Student [stuId=" + stuId + ", stuAge=" + stuAge + ", stuName=" + stuName + "]";
}

public Student(Integer stuId, Integer stuAge, String stuName) {
    super();
    this.stuId = stuId;
    this.stuAge = stuAge;
    this.stuName = stuName;
}
@Override
public int hashCode() {
    
    return stuName.hashCode()+stuAge;
}
@Override
public boolean equals(Object obj) {
    if(obj==null) {
        return false;
        
    }
    
    if(this==obj) {
        return true;
        
    }
    Student person=(Student)obj;//强转为Student类型
    //指定名字和年龄都相同就认为是同一个对象
    if(this.stuName.equals(person.getStuName())&&this.stuAge==person.getStuAge()) {
        
        return true;
    }else {
        return false;
    }
    
}

}
测试类:
package com.lx.dome;

import java.util.ArrayList;
import java.util.List;

public class StudentTest {
/**
 * 实现对象比较,如果名字和年龄都相同,就认为是同一个对象
 * 在Person类重写hashCode()和equals(Object obj)方法,并且添加相对应的判断条件逻辑
 * @param args
 */
public static void main(String[] args) {
    /**
     * 在stu1集合中不包含姓名年龄都相同的对象,输出为false
     */
    List<Student>stu1=new ArrayList<>();
    stu1.add(new Student(1, 22, "matureX"));
    stu1.add(new Student(2, 22, "cici"));
    stu1.add(new Student(3, 22, "sound"));
    stu1.add(new Student(4, 23, "coco"));
    System.out.println(stu1.contains(new Student(1, 22, "mature")));
    //在stu2集合中包含姓名年龄都相同的对象,输出为true
    List<Student>stu2=new ArrayList<>();
    stu2.add(new Student(1, 22, "mature"));
    stu2.add(new Student(2, 22, "cici"));
    stu2.add(new Student(3, 22, "sound"));
    stu2.add(new Student(4, 23, "coco"));
    System.out.println(stu2.contains(new Student(1, 22, "mature")));
}
}
运行结果:
false
true
原文地址:https://www.cnblogs.com/mature1021/p/9626608.html