java重写equals与hashCode,方便实体类如model,entity,pojo等安全存放于map,set中

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c5113620/article/details/88946554

java开发经常用到实体类作为orm层的数据交换对象,但是没有重写equals与hashCode会导致,在使用诸如set,map时的重复排序错误等等问题,所以equals与hashCode更有利于业务代码,方便使用map,set做去重,排序等等

注意,equals与hashCode中对于实体唯一性的判别,有时候只看id是否一致(实体id唯一性),有时候是多个属性决定唯一实体(id,name不能两个都一样)

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class Person {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int hashCode() {
        // depends on equals, unique property
        return Objects.hash(getId(),getName());
    }

    @Override
    public boolean equals(Object obj) {
        if(obj==null) return false;
        if(!(obj instanceof Person)) return false;
        Person person = (Person) obj;
        // combine all property that can identify unique book
        return Objects.equals(getId(),person.getId())
                && Objects.equals(getName(),person.getName());
    }

    public static void main(String[] args) {
        Person one = new Person(1,"one");
        Person two = new Person(1,"one");

        Map<Person,Integer> map = new HashMap<>();
        map.put(one,1);
        map.put(two,2); // will override 1 because one equals to two

        System.out.println(map.size());
        System.out.println(map.get(one));
        System.out.println(map.get(two));
    }
}

猜你喜欢

转载自blog.csdn.net/c5113620/article/details/88946554