• Java ArrayList对象集合去重


    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class StringSampleDemo {
        public static void main(String[] args) {
            ArrayList al = new ArrayList();
            al.add(new Student("zhangsan1", 20, "男"));
            al.add(new Student("zhangsan1", 20, "男"));
            al.add(new Student("lilin1", 21, "女"));
            al.add(new Student("lilin1", 21, "女"));
            al.add(new Student("lisi", 25, "男"));
    
            al = getUniqueList(al);
    
            for (Object o : al) {
                Student s = (Student) o;
                System.out.println(s.getName() + "...." + s.getAge() + "...." + s.getSex());
            }
    
            /** 去重后的集合数据
             *
             * zhangsan1....20....男
             * lilin1....21....女
             * lisi....25....男
             */
    
        }
    
        /**
         * 去除重复对象
         *
         * @param al
         * @return
         */
        public static ArrayList getUniqueList(ArrayList al) {
            ArrayList tempAl = new ArrayList();
    
            Iterator it = al.iterator();
            while (it.hasNext()) {
                Object obj = it.next();
                if (!tempAl.contains(obj)) //不存在则添加
                {
                    tempAl.add(obj);
                }
            }
            return tempAl;
        }
    }
    
    
    class Student {
        private String name;
        private int age;
        private String sex;
    
        public Student(String name, int age, String sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        /**
         * 重点是重写比较方法
         *
         * @param obj
         * @return
         */
        @Override
        public boolean equals(Object obj) {
            if (obj instanceof Student) {
                Student s = (Student) obj;
                return this.name.equals(s.name) && this.age == s.age && this.sex.equals(s.sex);
            } else {
                return false;
            }
        }
    }
    

      

  • 相关阅读:
    1941套站点模版,终生收藏,个个精品
    中文分词--逆向最大匹配
    解释抽象类继承实体类的前提是这个实体类必须明白构造函数
    iOS开发之解析XML格式数据
    在MyEclipse上部署Tomcatserver
    [BLE--Link Layer]物理信道
    项目实施准备事项
    【06】若不想使用编译器自动生成的函数,就该明确拒绝
    【05】了解C++默默编写并调用那些函数
    理解C# Attribute
  • 原文地址:https://www.cnblogs.com/smartsmile/p/11613006.html
Copyright © 2020-2023  润新知