gpt4 book ai didi

java - 删除每 n 个员工是行不通的

转载 作者:行者123 更新时间:2023-12-02 02:31:42 24 4
gpt4 key购买 nike

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 个元素,我该如何解决这个问题。我已经尝试了更多操作,但仍然不起作用

最佳答案

每当您想从列表中删除元素时,请使用迭代器。

尝试下面的代码:

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++;
}
}

关于java - 删除每 n 个员工是行不通的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46990095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com