package cn.itacst.p3.arraylist.test;
import java.util.ArrayList;
import java.util.Iterator;
/*
* 定义功能去除ArrayList中的重复元素
*/
public class ArrayListTest2 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("abc1");
al.add("abc2");
al.add("abc1");
al.add("abc2");
al.add("abc");
System.out.println(al);
al = getSingleElement(al);
System.out.println(al);
}
public static ArrayList getSingleElement(ArrayList al) {
//定义一个临时容器
ArrayList temp = new ArrayList();
//迭代al集合
Iterator it = al.iterator();
while(it.hasNext()){
Object obj = it.next();
//判断被迭代到的元素是否存在临时容器中
if(!temp.contains(obj)){
temp.add(obj);
}
}
return temp;
}
}
|
|