import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class vijftienpunt1 {

public static void downsize(LinkedList<String> employeeNames, int n) {
    for (int i = 0; i < employeeNames.size(); i++) {
        if(i%n==0) {
            employeeNames.remove(i);
        }
    }
}

public static void main(String[] args) {
    LinkedList<String> employeeNamess = new LinkedList<String>();

    employeeNamess.add("Ab");

    employeeNamess.add("Yo");
    employeeNamess.add("Ik");
    employeeNamess.add("Jij");

    System.out.println(employeeNamess);
    downsize(employeeNamess, 2);
    System.out.println(employeeNamess);
}
}


当我运行该命令不起作用时,它将删除其他第n个元素,我该如何解决。我尝试了更多操作,但仍然无法正常工作

最佳答案

每当您要从列表中删除元素时,请使用Iterator。

试试下面的代码:

public static void downsize(LinkedList<String> employeeNames, int n) {
    int i=1;
    Iterator<String> iter=employeeNames.iterator();
    while(iter.hasNext()){
        iter.next();
        if(i%n==0) {
            iter.remove();
        }
        i++;
    }
}

10-07 18:37