从基本数组中删除元素 [英] Removing an element from a primitive array

查看:102
本文介绍了从基本数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

还有其他选择吗?我不能使用任何第三方/附加库

Any alternative to that? I can not use any third party/additional libraries

推荐答案

您需要创建一个新数组并复制元素.例如像这样的东西:

You need to create a new array and copy the elements; e.g. 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 ....

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

You could also do the copying using for loops, but arraycopy should be faster in this case.

org.apache.commons.lang.ArrayUtils.remove(long[], int)方法最有可能像上面的代码一样工作.如果不需要避免使用第三方开放源代码库,则最好使用该方法. (@Srikanth Nakka为知道/找到它而致以荣誉.)

The org.apache.commons.lang.ArrayUtils.remove(long[], int) method most likely works like the above code. Using that method would be preferable ... if you were not required to avoid using 3rd-party open source libraries. (Kudos to @Srikanth Nakka for knowing / finding it.)

之所以不能使用列表来执行此操作,是因为列表要求元素类型是引用类型.

The reason that you can't use an list to do this is that lists require an element type that is a reference type.

这篇关于从基本数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆