List A和B
A.removeAll(B); A.addAll(B);
例如有如下实体类:
/** * hashset是如何保持元素的唯一性呢? * 是通过元素的hashcode和equals来表示: * 如果hashCode值一样,则比较equals是否为true * 如果hashCode值不一样,不用比较equals */
/** * List是如何集合中元素相同的呢? * 是通过元素的hashcode和equals来表示: * 如果hashCode值一样,则比较equals是否为true * 如果hashCode值不一样,不用比较equals */
public class UserTable { private String linkdoodid; private String linkdoodname;
public UserTable() { super(); }
public UserTable(String linkdoodid,String linkdoodname){
supert();
this.linkdoodid=linkdoodid;
this.linkdoodname=linkdoodname;
} public String getLinkdoodid() { return linkdoodid; } public void setLinkdoodid(String linkdoodid) { this.linkdoodid = linkdoodid == null ? null : linkdoodid.trim(); } public String getLinkdoodname() { return linkdoodname; } public void setLinkdoodname(String linkdoodname) { this.linkdoodname = linkdoodname == null ? null : linkdoodname.trim(); } @Override public boolean equals(Object obj) { if (!(obj instanceof UserTable)) { return false; } UserTable userTable = (UserTable) obj; return this.linkdoodid.equals(userTable.linkdoodid); } @Override public int hashCode() { return linkdoodid.hashCode(); } }
测试:
public class HashSetTest { public static void main(String[] args) {
//List
List<UserTable> listA=new ArrayList<UserTable>();
listA.add(new UserTable("A1001","LJ"));
listB.add(new UserTable("B1002","MH"));
List<UserTable> listB=new ArrayList<UserTable>();
listB.add(new UserTable("B1002","SM"));
listB.add(new UserTable("C1001","TM"));
listA.removeAll(listB);//由于UserTable的hashCode和equal 都是以linkdoodid 来判断,所以“B1002”算重复元素
listA.addAll(listB);
//HashSet HashSet<UserTable> hs = new HashSet<UserTable>(); hs.add(new UserTable("a1", 20)); hs.add(new UserTable("a2", 30)); hs.add(new UserTable("a3", 40)); hs.add(new UserTable("a3", 40)); Iterator<Person> iterator = hs.iterator(); while(iterator.hasNext()){ Person p = iterator.next(); System.out.println(p.getName()+" "+p.getAge()); } } }