gpt4 book ai didi

java - 如何删除数组中元素值的第一个实例?

转载 作者:行者123 更新时间:2023-11-29 02:58:02 27 4
gpt4 key购买 nike

Add a method void removeFirst(int newVal) to the IntegerList class that removes the first occurrence of a value from the list. If the value does not appear in the list, it should do nothing (but it's not an error). Removing an item should not change the size of the array, but note that the array values do need to remain contiguous, so when you remove a value you will have to shift everything after it down to fill up its space. Also remember to decrement the variable that keeps track of the number of elements.

请帮忙,我已经尝试了本网站上列出的所有其他关于“从数组中删除元素”的解决方案,但都没有奏效。

最佳答案

此方法支持与 Collection.remove() 相同的功能,后者是 ArrayList 删除第一个匹配元素的方式。

public boolean remove(int n) {
for (int i = 0; i < size; i++) {
if (array[i] != n) continue;
size--;
System.arraycopy(array, i + 1, array, i, size - i);
return true;
}
return false;
}

与其自己编写此代码,我建议您查看 Trove4J 的 TIntArrayList,它是 int[] 的包装器。您还可以阅读 ArrayList 的代码以了解如何这是写的。

关于java - 如何删除数组中元素值的第一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5527712/

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