java实体类中,对某些属性进行equals和hashCode设定,通过对设定属性来判断对象是否相等

实体类

package demo12;
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 PreStudent {
    private Integer id;
    private String name;
    private String age;
    private String address;
    /**
     * 写equals和hashCode的意义,对象name,age,只要这两个相同就认为这个两个对象相等
     */
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PreStudent that = (PreStudent) o;
        return name.equals(that.name) && age.equals(that.age);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

测试

package demo12;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestEqualsHash {
    public static void main(String[] args) {
        PreStudent p1 = new PreStudent(1,"张三","33","河南");
        PreStudent p2 = new PreStudent(2,"李四","36","郑州");
        PreStudent p3 = new PreStudent(3,"王五","13","洛阳");
        PreStudent p4 = new PreStudent(4,"赵六","93","周口");
        List preStudents = Arrays.asList(p1, p2, p3, p4);
        PreStudent a1 = new PreStudent(22,"张三","33","广东");
        // 判断a1是否存在于preStudents集合中,因为已经写了equals和hashCode方法中的,name,age所以,只要这两个属性值相等,就可以认为对象相等
        boolean contains = preStudents.contains(a1);
        System.out.println(contains);  // true
        // 测试2
        PreStudent b1 = new PreStudent(61,"小红","56","哈尔滨");
        PreStudent b2 = new PreStudent(62,"赵六","93","吉林");
        PreStudent b3 = new PreStudent(63,"王五","13","北京");
        List nowStudents = Arrays.asList(b1, b2, b3);

        // 判断NowStudents存在几个与preStudents相同的
        List equalsStudents = new ArrayList<>();

        for (PreStudent nowStudent : nowStudents) {
            if(preStudents.contains(nowStudent)) {
                equalsStudents.add(nowStudent);
            }
        }
        System.out.println(equalsStudents);
        // [PreStudent(id=62, name=赵六, age=93, address=吉林), PreStudent(id=63, name=王五, age=13, address=北京)]
    }
}

你可能感兴趣的:(java,开发语言)