【Java】重载equals和hashCode方法,以保证程序以雇员的id和姓名相同作为雇员实例相同的条件
如果场景中要求对象属性相同即判定为相等,那不能用==,因为==实际是在比地址,只有引用地址相同的实例才会返回true;而需要重载equals和hashCode方法,书写自己的比较规则。
代码:
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public class Emp { private long id; private String name; public Emp(long id,String name) { this.id=id; this.name=name; } public Emp() { this(-1,null); } @Override public boolean equals(Object o) { if(this==o) { return true; } if(o==null || this.getClass()!=o.getClass()) { return false; } Emp emp=(Emp)o; return id==emp.id && Objects.equals(name, emp.name); } @Override public int hashCode() { return Objects.hash(id,name); } public String toString() { return "#"+id+" "+name; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { List<Emp> ls=new ArrayList<>(); ls.add(new Emp(1,"Andy")); ls.add(new Emp(1,"Andy")); ls.add(new Emp(2,"Bill")); ls.add(new Emp(2,"Bill")); ls.add(new Emp(2,"Bill")); ls.add(new Emp(3,"Cindy")); ls.add(new Emp(3,"Cindy")); ls.add(new Emp(3,"Cindy")); ls.add(new Emp(3,"Cindy")); Map<Emp,Integer> map=new HashMap<>(); for(Emp emp:ls) { if(map.containsKey(emp)) { int count=map.get(emp); count++; map.put(emp, count); }else { map.put(emp, 1); } } for(Map.Entry<Emp, Integer> it:map.entrySet()) { System.out.println(it.getKey()+" took place "+it.getValue()+" times."); } } }
输出:
#2 Bill took place 3 times. #3 Cindy took place 4 times. #1 Andy took place 2 times.
END