原理根据Set的特性,另外需要重写对象的hashCode()方法和equals()方法
代码如下
package com.pingan.home.tets; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Set; public class Person { private String name; private String addr; public Person(String name, String addr) { super(); this.name = name; this.addr = addr; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((addr == null) ? 0 : addr.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (addr == null) { if (other.addr != null) return false; } else if (!addr.equals(other.addr)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public static void main(String[] args) { ArrayList<Person> persoList = new ArrayList<Person>(); for (int i = 0; i < 10; i++) { Person p = new Person("w", "j" + i); persoList.add(p); } Person p1 = new Person("w", "j" + 1); Person p2 = new Person("w", "j" + 5); Person p3 = new Person("w", "j" + 0); Person p4 = new Person("w", "j" + 9); persoList.add(p1); persoList.add(p2); persoList.add(p3); persoList.add(p4); System.out.println("persoList.size() s:" + persoList.size()); Set<Person> set = new LinkedHashSet<Person>(persoList); persoList.clear(); persoList.addAll(set); System.out.println("persoList.size() e:" + persoList.size()); } }
时间: 2024-10-13 09:20:03