我想创建一个方法,从一个未知类型的List中删除每个第N个元素,然而,无论我如何尝试,它都不能删除指定的元素,但我无法弄清楚为什么。我已经苦苦挣扎了两天,所以现在把它发布到这里作为最后一招。提前感谢您的任何帮助。
我目前的代码如下:
public static void removeEveryNthElement(List<?> list, int n) {
//Set list equal to an ArrayList because List is immutable
list = new ArrayList<>(list);
//If n is negative or zero throw an exception
if(n <= 0) {
throw new IllegalArgumentException("Integer n needs to be a positive number.");
}
//If the list is null, throw an exception
if(list == null) {
throw new NullPointerException("The list must not be null.");
}
//Remove every nth element in the list
for(int i = 0; i < list.size(); i++) {
if(i % n == 0) {
list.remove(i);
}
}
我尝试过的另一种方法是使用以下代码替换for循环:
list.removeIf(i -> i % 3 == 0);
但是,当我这样做时,我收到了一个错误,指出参数类型不支持 % 运算符。 我还尝试使用 for 循环,将列表中的每个元素单独添加到另一个可修改的列表中,但无论我做什么,都没有成功。如果您能帮助我解决这个问题,我将非常感激!
list = new ArrayList<>(list);
创建了该列表的副本。只有该副本被修改,您需要返回已更改的副本。 - Thomas Kläger