ArrayList去除集合中的相同内容
1、ArrayList去除集合中的相同内容
创建新集合将重复元素去掉:
-
明确返回值类型,返回ArrayList
-
明确参数列表ArrayList
分析:
1、创建新集合
2、根据传入的集合(老集合)获取迭代器
3、遍历老集合
4、通过新集合判断是否包含老集合中的元素,如果包含就不添加,如果不包含就添加
import java.util.ArrayList;
import java.util.Iterator;
/**
*ArrayList去除集合中的相同内容
*/
public class Demo01 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
//随便添加点元素
list.add("q");
list.add("q");
list.add("s");
list.add("s");
list.add("df");
list.add("f");
list.add("v");
ArrayList newList = getSingle(list);
System.out.println(newList);
}
public static ArrayList getSingle(ArrayList list){
//1、创建新集合
ArrayList newList = new ArrayList();
//2、根据传入的集合(老集合)获取迭代器
Iterator it = list.iterator();
// 3、遍历老集合
while(it.hasNext()){
Object obj = it.next();
// 4、通过新集合判断是否包含老集合中的元素,如果包含就不添加,如果不包含就添加
if(!newList.contains(obj)){
newList.add(obj);
}
}
return newList;
}
}
运行结果:
2、ArrayList去除集合中自定义对象元素的重复值
首先自定义一个对象:
public class Person {
private String name;
private int age;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
假定,姓名和年龄相同即为一个人,然后我们用和上一个案例相同的方法运行一遍:
import java.util.ArrayList;
import java.util.Iterator;
import com.nm.bean.Person;
/**
*
* ArrayList去除集合中自定义对象元素的重复值
*/
public class Demo02 {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(new Person("张三", 24));
list.add(new Person("张三", 24));
list.add(new Person("张三", 24));
list.add(new Person("李四", 24));
list.add(new Person("李四", 24));
list.add(new Person("李四", 24));
ArrayList newList = getSingle(list);
System.out.println(newList);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static ArrayList getSingle(ArrayList list){
//1、创建新集合
ArrayList newList = new ArrayList();
//2、根据传入的集合(老集合)获取迭代器
Iterator it = list.iterator();
// 3、遍历老集合
while(it.hasNext()){
Object obj = it.next();
// 4、通过新集合判断是否包含老集合中的元素,如果包含就不添加,如果不包含就添加
if(!newList.contains(obj)){
newList.add(obj);
}
}
return newList;
}
}
运行结果:
不难发现,集合中相同的元素并未删除,为什么呢?
我们像集合中添加元素的方法都是new的,虽然值相同,但是他们的地址是不同的。通过查询contains
源码不难发现,contains
方法判断是否包含,底层依赖的是equals
方法的,所以我们要在Person
类中重写equals方法。
public boolean equals(Object obj) {
// TODO Auto-generated method stub
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
重写equals方法之后我们再运行,就会发现相同的元素都被删除了。