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

标签 java arrays

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/

相关文章:

java - 使用具有给定模数和指数的 RSA 算法在 Android 中加密

javascript - TypeError : undefined is not an object , 项目来自 API 的数组

arrays - 从 numpy 数组计算峰度?

javascript - 替换 JSON 对象中的值

java - 无法在java中使用循环分配数组值

java - 使用 Hibernate 执行数千次插入时 CPU 利用率高

java - 访问 arraylist 数组中的元素

java - 如何随机设置按钮的图像?

python - 为什么 (2^31) >> 32 不是 0?

java - 公开 junit 的虚拟 URL