List去重问题
如果集合中的数据类型是基本数据类型,可以直接将list集合转换成set,就会自动去除重复的元素,这个就相对比较简单。
public class Test { public static void main(String[] args) { List list = new ArrayList(); list.add(11); list.add(12); list.add(13); list.add(14); list.add(15); list.add(11); System.out.println(list); Set set = new HashSet(); List newList = new ArrayList(); set.addAll(list); newList.addAll(set); System.out.println(newList); } }
当list集合中存储的类型是对象类型的时候,我们就不能简单的只把list集合转换成set集合。
我们定义一个对象类:
public class People { private String name; private String phoneNumber; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public People(String name, String phoneNumber) { super(); this.name = name; this.phoneNumber = phoneNumber; } @Override public String toString() { return "People{" + "name='" + name + ''' + ", phoneNumber='" + phoneNumber + ''' + '}'; } }
当list集合中存储的是对象时,我们需要在对象的实体类中去重写equals()方法和hashCode()方法,如下:
public class People { private String name; private String phoneNumber; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public People(String name, String phoneNumber) { super(); this.name = name; this.phoneNumber = phoneNumber; } @Override public String toString() { return "People{" + "name='" + name + ''' + ", phoneNumber='" + phoneNumber + ''' + '}'; } @Override public boolean equals(Object arg0) { // TODO Auto-generated method stub People p = (People) arg0; return name.equals(p.name) && phoneNumber.equals(p.phoneNumber); } @Override public int hashCode() { // TODO Auto-generated method stub String str = name + phoneNumber; return str.hashCode(); } }
test:
public static void main(String[] args) { List<People> listPeople = new ArrayList<People>(); listPeople.add(new People("张三", "11111")); listPeople.add(new People("张三", "22222")); listPeople.add(new People("李四", "33333")); listPeople.add(new People("张三", "22222")); Set<People> setData = new HashSet<People>(); setData.addAll(listPeople); System.out.println("list:" + listPeople.toString()); System.out.println("set:" + setData.toString()); }
此时运行上面的test方法,去重就成功了。