重写Java Object对象的hashCode和equals方法实现集合元素按内容判重

来源:互联网 发布:获取手机的gps数据 编辑:程序博客网 时间:2024/05/01 23:12

Java API提供的集合框架中Set接口下的集合对象默认是不能存储重复对象的,这里的重复判定是按照对象实例句柄的地址来判定的,地址相同则判定为重复,地址不同不管内容如何都判定为不重复,这有时与需求不符,可以通过重写hashCode和equals方法实现按照集合元素的任意内容判定重复。

public class Employee implements Cloneable{private int id;private String name;public Employee(int id, String name){super();this.id = id;this.name = 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;}@Overridepublic int hashCode(){return this.getId();}@Overridepublic boolean equals(Object obj){if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Employee other = (Employee) obj;if (id != other.id)return false;return true;}@Overrideprotected Employee clone() throws CloneNotSupportedException{return (Employee) super.clone();}}

public class Test{public static void main(String[] args) throws CloneNotSupportedException{Set<Employee> set = createEmployeeSet();System.err.println(set.size());for (Employee e : set){System.out.println(e.getId() + "  " + e.getName());}}public static Set<Employee> createEmployeeSet()throws CloneNotSupportedException{Set<Employee> set = new HashSet<Employee>();Employee e1 = new Employee(1, "xmc1");Employee e2 = new Employee(2, "xmc2");Employee e3 = e1.clone();Employee e4 = new Employee(2, "xmc3");set.add(e1);set.add(e2);set.add(e3);set.add(e4);return set;}}


0 0
原创粉丝点击