zoukankan      html  css  js  c++  java
  • Java List合并去重

    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());   } } }
  • 相关阅读:
    C#实现注册码
    多表链接 Left join
    Repeater 一行显示两列数据
    Repeater一行显示数据库中多行表记录
    HP QC(Quality Center)在Windows 7 IE8 IE9下不能工作解决方案
    Android应用换肤总结
    Lua 第一个应用程序 Hello World
    JNI 技术与 Android 应用
    NSAutoreleasePool' is unavailable: not avail
    1-2基础控件
  • 原文地址:https://www.cnblogs.com/liaojie970/p/6236609.html
Copyright © 2011-2022 走看看