您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从基本数组中删除元素

从基本数组中删除元素

您需要创建一个新数组并复制元素。例如这样的事情:

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

注意:以上尚未经过测试/调试。

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

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

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

其他 2022/1/1 18:34:12 有439人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶