去除重复元素:
public static ArrayList singleElement(ArrayList al) { //定义一个临时容器 ArrayList newAl = new ArrayList(); Iterator it = al.iterator(); while (it.hasNext()) { Object obj = it.next(); if (!newAl.contains(obj)) { newAl.add(obj); } } return newAl; }
自定义对象作为元素存到ArrayList中,并去除重复元素。
比如:存人对象。同姓名同年龄,视为同一个人,去除重复。
import java.util.ArrayList; import java.util.Iterator; public class ArrayListDemo { public static void main(String[] args) { ArrayList al = new ArrayList(); al.add(new Person("lisi01", 30)); al.add(new Person("lisi02", 31)); al.add(new Person("lisi03", 32)); al.add(new Person("lisi04", 33)); al.add(new Person("lisi04", 33)); al.add(new Person("lisi04", 33)); al = singleElement(al); Iterator it = al.iterator(); while (it.hasNext()) { Person p = (Person) it.next(); System.out.println(p.getName() + "--" + p.getAge()); } } public static ArrayList singleElement(ArrayList al) { //定义一个临时容器 ArrayList newAl = new ArrayList(); Iterator it = al.iterator(); while (it.hasNext()) { Object obj = it.next(); if (!newAl.contains(obj)) { newAl.add(obj); } } return newAl; } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object obj) { if (!(obj instanceof Person)) return false; Person p = (Person) obj; return this.getName().equals(p.name) && this.getAge() == p.age; } 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; } }
List集合判断元素是否相等,依据是元素的equals方法,contains调用的底层是equals方法,remove调用底层也是equals方法。
原文地址:https://www.cnblogs.com/hongxiao2020/p/12638163.html
时间: 2024-11-05 21:43:32