代码如下:
class ArrayListTest1 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("java03");
al.add("java03");
al.add("java01");
al.add("java02");
al.add("java01");
al.add("java02");
al.add("java01");
System.out.println(al);
al = singleElement(al);
System.out.println(al);
}
//返回List合适些
public static ArrayList singleElement(ArrayList al){
//定义一个临时容器
ArrayList newAl = new ArrayList();
//在迭代是循环中next调用一次,就要hasNext判断一次
Iterator it = al.iterator();
while (it.hasNext()){
Object obj = it.next();//next()最好调用一次就hasNext()判断一次否则容易发生异常
if (!newAl.contains(obj))
newAl.add(obj);
}
return newAl;
}
}