正确生成hashCode和equals方法,以及联合set集合达到去重目的

Idea自动生成HashCode和equals视频链接

https://live.csdn.net/v/330419

正确生成hashCode和equals方法,以及联合set集合达到去重目的_第1张图片

实体类 对name和age两个属性重写hashCode,equals方法

package TestEqualsHashCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.Objects;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Student {
    private String name;
    private int age;
    private String address;
    private String school;
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

测试

@Test
    public void test1(){
        Student s1 = new Student("张三",11,"河南","太康");
        Student s2 = new Student("李四",66,"郑州","扶沟");
        Student s3 = new Student("张三",11,"河北","武汉");
        Student s4 = new Student("李四",66,"广东","深圳");

        Set students = new HashSet<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);
        System.out.println(students);
    }

运行结果

[Student(name=李四, age=66, address=郑州, school=扶沟), Student(name=张三, age=11, address=河南, school=太康)]

你可能感兴趣的:(java)