从基本数组中删除元素

Nis*_*ain 1 java arrays primitive-types

我有一个原始类型数组,我想从中删除指定索引处的元素.这样做的正确有效方法是什么?

我希望以下面提到的方式删除元素

long[] longArr = {9,8,7,6,5};
int index = 1;

List list = new ArrayList(Arrays.asList(longArr));
list.remove(index);
longArr = list.toArray(); // getting compiler error Object[] can't be converted to long[]
Run Code Online (Sandbox Code Playgroud)

但上面的方法看起来只与Object一起使用而不与原语一起使用.

除此之外的其他选择?我不能使用任何第三方/额外的库

Ste*_*n C 5

您需要创建一个新数组并复制元素; 例如:

public long[] removeElement(long[] in, int pos) {
    if (pos < 0 || pos >= in.length) {
        throw new ArrayIndexOutOfBoundsException(pos);
    }
    long[] res = new long[in.length - 1];
    System.arraycopy(in, 0, res, 0, pos);
    if (pos < in.length - 1) {
        System.arraycopy(in, pos + 1, res, pos, in.length - pos - 1);
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

注意:以上内容尚未经过测试/调试....

您也可以使用for循环进行复制,但arraycopy在这种情况下应该更快.

org.apache.commons.lang.ArrayUtils.remove(long[], int)方法最有可能像上面的代码一样工作.如果您不需要避免使用第三方开源库,那么使用该方法将更可取.(感谢@Srikanth Nakka知道/找到它.)

您无法使用列表执行此操作的原因是列表需要一个引用类型的元素类型.