package com.aaa.demo;
import java.util.ArrayList;
import java.util.Iterator;
class demo1_去除集合中重复元素 {
/**
* 需求:去除集合中重复元素
* 思路:主要思想,判断是否包含相同元素,传入新创建的集合。
* 步骤:1.
*/
public static void main(String[] args) {
//demo1();
ArrayList<String> li = new ArrayList<>();
li.add("a");
li.add("b");
li.add("c");
li.add("c");
li.add("e");
System.out.println(li);
ArrayList<String> newlist = getSingle(li);
System.out.println(newlist);
}
public static ArrayList<String> getSingle(ArrayList list){
ArrayList<String> newlist = new ArrayList<>();
Iterator<String> it = list.iterator();
while(it.hasNext()){
if(!newlist.contains(it.next()));
newlist.add(it.next());
}
return newlist;
}
报错:Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:834)
at com.aaa.demo.demo1_去除集合中重复元素.getSingle(demo1_去除集合中重复元素.java:31)
at com.aaa.demo.demo1_去除集合中重复元素.main(demo1_去除集合中重复元素.java:22)
|
|