[one_demo_13]ArrayList去除重复的元素
ArrayList底层采用数组结构,查询快,增删慢,线程不安全,效率高。在开发中会用到。存储量大的数据时,有时候需要将集合中重复的元素或者有重复内容的元素去除掉。总体来说,约有两种思路,一种是新建集合,遍历旧集合,将旧集合中的元素一个一个add到新集合,add时如果这个元素没有在新集合中则添加;第二种思路是,直接在旧集合中remove,采用选择排序法的思路,遍历集合(第一层循环),将集合的每一个元素与其后的所有元素比较(第二层循环),采用equals比较(注意如果是自定义的类需要重写equals方法),如果返回true,则remove这个被比较的元素,同时将二层循环的步数-1,以免遗漏比较的元素。
代码实现
Demo1新建集合过滤添加:
public static void test11() {
ArrayList oldList = new ArrayList();
ArrayList newList = new ArrayList();
Student s1 = new Student("haha1", 12);
Student s2 = new Student("haha2", 12);
Student s3 = new Student("haha3", 12);
Student s4 = new Student("haha4", 12);
Student s5 = new Student("haha1", 12);
Student s6 = new Student("haha1", 12);
Student s7 = new Student("haha2", 13);
Student s8 = new Student("haha4", 13);
Student s9 = new Student("haha1", 13);
Student s10 = new Student("haha2", 12);
Student s11 = new Student("haha3", 12);
Student s12 = new Student("haha4", 12);
oldList.add(s1);
oldList.add(s2);
oldList.add(s3);
oldList.add(s4);
oldList.add(s5);
oldList.add(s6);
oldList.add(s7);
oldList.add(s8);
oldList.add(s9);
oldList.add(s10);
oldList.add(s11);
oldList.add(s12);
int flag = 1;
for (Iterator it = oldList.iterator(); it.hasNext();) {
Student stu = (Student) it.next();
if (!newList.contains(stu)) {
newList.add(stu);
}
}
System.out.println(newList);
}
学生类略,注意重写equals方法。
Demo2在原集合中直接过滤:
public static void test12() {
ArrayList oldList = new ArrayList();
ArrayList newList = new ArrayList();
Student s1 = new Student("haha1", 12);
Student s2 = new Student("haha2", 12);
Student s3 = new Student("haha3", 12);
Student s4 = new Student("haha4", 12);
Student s5 = new Student("haha1", 12);
Student s6 = new Student("haha1", 12);
Student s7 = new Student("haha2", 13);
Student s8 = new Student("haha4", 13);
Student s9 = new Student("haha1", 13);
Student s10 = new Student("haha2", 12);
Student s11 = new Student("haha3", 12);
Student s12 = new Student("haha4", 12);
oldList.add(s1);
oldList.add(s2);
oldList.add(s3);
oldList.add(s4);
oldList.add(s5);
oldList.add(s6);
oldList.add(s7);
oldList.add(s8);
oldList.add(s9);
oldList.add(s10);
oldList.add(s11);
oldList.add(s12);
for (int i = 0; i < oldList.size() - 1; i++) {
for (int j = i + 1; j < oldList.size(); j++) {
Student ss1 = (Student) oldList.get(i);
Student ss2 = (Student) oldList.get(j);
if (ss1.equals(ss2)) {
oldList.remove(j);
j--;
}
}
}
System.out.println(oldList);
}