方法一: 通过Iterator 的remove方法
- public void testList() {
- List<Integer> list=new ArrayList<Integer>();
- list.add(1);
- list.add(2);
- list.add(4);
- list.add(1);
- list.add(2);
- list.add(5);
- list.add(1);
- List<Integer> listTemp= new ArrayList<Integer>();
- Iterator<Integer> it=list.iterator();
- while(it.hasNext()){
- int a=it.next();
- if(listTemp.contains(a)){
- it.remove();
- }
- else{
- listTemp.add(a);
- }
- }
- for(Integer i:list){
- System.out.println(i);
- }
- }
方法二:直接将结果赋值给另一个List
- public void testList2() {
- List<Integer> list=new ArrayList<Integer>();
- list.add(1);
- list.add(2);
- list.add(4);
- list.add(1);
- list.add(2);
- list.add(5);
- list.add(1);
- List<Integer> tempList= new ArrayList<Integer>();
- for(Integer i:list){
- if(!tempList.contains(i)){
- tempList.add(i);
- }
- }
- for(Integer i:tempList){
- System.out.println(i);
- }
- }