利用Java迭代器删除list中元素

时间:2022-02-26 20:48:14

利用Java迭代器删除list中元素

昨天晚上,老师问了一个问题:Java中怎么删除list中指定位置的元素,提示是用迭代器。简单实现如下:


import java.awt.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;

public class test {

    static void printRemove(String str, int i){
        System.out.println(str + i);
        System.out.println("----------------Remove-------------");
    }

    static void printVerify(String str, int i){
        System.out.println(str + i);
        System.out.println("----------------Verify-------------");
    }

    public static void main(String[] args) throws Exception{


        ArrayList<String> listTest = new ArrayList<String>();
        LinkedList<String> ls = new LinkedList<String>();


        listTest.add(0,"A");
        listTest.add(1,"B");
        listTest.add(2,"C");
        listTest.add(3,"D");

        ls.add("1");
        ls.add("2");
        ls.add("3");
        ls.add("4");

        int i = 0;
        for (Iterator<String> iter =  listTest.iterator(); iter.hasNext();i++) {

            String str = (String)iter.next();

              if(i%2!=0){

              iter.remove();

              printRemove(str,i);

              }
              printVerify(str,i);
             }

        for (Iterator<String> iter =  listTest.iterator(); iter.hasNext();) {
              System.out.println();
            String str = (String)iter.next(); 
              System.out.println(str);

             }


        for (Iterator<String> iter1 = ls.iterator(); iter1.hasNext();i++) {

            String str = (String)iter1.next();

              if(i%2!=0){

              iter1.remove();

              printRemove(str,i);

              }
              printVerify(str,i);
             }

        for (Iterator<String> iter =  ls.iterator(); iter.hasNext();) {
              System.out.println();
            String str = (String)iter.next(); 
              System.out.println(str);

             }

             }
    }   



简单实现了删除偶数位置的元素。
实现了功能,未考虑性能优化。