简体   繁体   English

从原始数组中删除元素

[英]Removing an element from a primitive array

I have a primitive type array from which I want to remove an element at the specified index.我有一个原始类型数组,我想从中删除指定索引处的元素。 What is the correct and efficient way to do that?什么是正确和有效的方法来做到这一点?

I am looking to remove the element in the way mentioned below我希望以下面提到的方式删除元素

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[]

but the above approach looks to work with with Object only not with primitives.但上述方法看起来只适用于 Object 而不适用于基元。

Any alternative to that?有什么替代方法吗? I can not use any third party/additional libraries我不能使用任何第三方/附加库

You need to create a new array and copy the elements;您需要创建一个新数组并复制元素; eg something like this:例如这样的事情:

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

NB: the above has not been tested / debugged ....注意:以上内容尚未经过测试/调试....

You could also do the copying using for loops, but arraycopy should be faster in this case.您也可以使用 for 循环进行复制,但在这种情况下arraycopy应该更快。

The org.apache.commons.lang.ArrayUtils.remove(long[], int) method most likely works like the above code. org.apache.commons.lang.ArrayUtils.remove(long[], int)方法很可能像上面的代码一样工作。 Using that method would be preferable ... if you were not required to avoid using 3rd-party open source libraries.使用该方法会更可取……如果您不需要避免使用 3rd-party 开源库。 (Kudos to @Srikanth Nakka for knowing / finding it.) (感谢@Srikanth Nakka 知道/找到它。)

The reason that you can't use an list to do this is that lists require an element type that is a reference type.不能使用列表来执行此操作的原因是列表需要作为引用类型的元素类型。

In addition to the answer by StephenC, have a look at https://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html .除了 StephenC 的回答,请查看https://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html

It explains java arrays pretty well.它很好地解释了 java 数组。

Use org.apache.commons.lang.ArrayUtils.使用 org.apache.commons.lang.ArrayUtils。

long[] longArr = {9,8,7,6,5};
int index = 1;
longArr=ArrayUtils.remove(longArr, index);
Integer[] arr = new Integer[] {100,150,200,300};

List<Integer> filtered = Arrays.asList(arr).stream()
    .filter(item -> item < 200)
    .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM