如何向数组中添加元素并移动索引?

19

我需要在数组中指定位置和值添加一个元素。 举个例子,我有一个数组:

int []a = {1, 2, 3, 4, 5, 6};

应用addPos(int 4, int 87)后,它应该是

int []a = {1, 2, 3, 4, 87, 5};

我知道这里应该对数组的索引进行移位,但不知道如何在代码中实现它。


1
在Java中,您无法移动数组的索引。数组是固定大小的。创建一个具有所需值的新数组,并将引用“a”分配给新数组。 - kosa
作业?如果是,请标记为作业。 - user166390
现在为时已晚,因为已经有完整的代码答案了。 - Marko Topolnik
3
使用ArrayUtils.add(T[] array, int index,T element)方法可以在Java中向数组中添加元素。该方法将一个指定的元素插入到指定索引处,并将原数组中的所有元素向右移动,以给新元素留出空间。最后,该方法返回一个包含新元素的新数组。要使用该方法,您需要导入Apache Commons Lang库。 - Tadeu Jr.
15个回答

16
最简单的方法是使用一个 ArrayList<Integer> 并使用 add(int, T) 方法。
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);

// Now, we will insert the number
list.add(4, 87);

2
该方法是add(int index, T element),而不是insert - daniel kullmann
1
该操作要求特定使用数组。 - Fran Marzoa
@FranMarzoa 你可以将数组转换为列表,然后在最后将列表转换为数组。 - FullStackDeveloper
它具有大量包装整数的开销。 替代方案: https://fastutil.di.unimi.it/docs/it/unimi/dsi/fastutil/ints/IntList.html#add(int,int) https://www.eclipse.org/collections/javadoc/10.4.0/org/eclipse/collections/impl/list/mutable/primitive/IntArrayList.html#addAtIndex(int,int) - Dmitry Ovchinnikov

14

这应该可以解决问题:

public static int[] addPos(int[] a, int pos, int num) {
    int[] result = new int[a.length];
    for(int i = 0; i < pos; i++)
        result[i] = a[i];
    result[pos] = num;
    for(int i = pos + 1; i < a.length; i++)
        result[i] = a[i - 1];
    return result;
}

其中,a是原始数组,pos是插入位置,num是要插入的数字。


14
System.arraycopy 会是一个更好的解决方案。 - Marko Topolnik
确实,我不知道那个是内置的。 - jrad
1
for(int i = pos + 1; i < a.length; i++) 应该是 result.length 不是吗? - SüniÚr

10

Jrad的解决方案不错,但我不喜欢他没有使用数组复制。内部System.arraycopy()进行本机调用,因此您将获得更快的结果。

public static int[] addPos(int[] a, int index, int num) {
    int[] result = new int[a.length];
    System.arraycopy(a, 0, result, 0, index);
    System.arraycopy(a, index, result, index + 1, a.length - index - 1);
    result[index] = num;
    return result;
}

9
你必须创建一个新数组,使用System.arraycopy复制前缀和后缀,并将那个位置设置为新值。

6

如果你喜欢使用Apache Commons而不是重复造轮子,当前的方法如下:

a = ArrayUtils.insert(4, a, 87);

以前是用 ArrayUtils.add(...),但现在已经被弃用了。这里有更多信息:1


4

我闻到了作业的味道,所以可能不允许使用ArrayList (?)

与其寻找“移动索引”的方法,不如直接构建一个新的数组:

int[] b = new int[a.length +1];

然后

  1. 从零开始计数,将数组a的索引复制到插入位置
  2. ...
  3. ...

//编辑:当然是复制值,而不是索引


4

除非我漏看了什么,这个问题并不是关于增加数组大小的。在这个例子中,数组大小保持不变。(就像位移一样。) 在这种情况下,没有必要创建一个新数组或复制它。这应该可以解决问题:

static void addPos(int[] array, int pos, int value) {
    // initially set to value parameter so the first iteration, the value is replaced by it
    int prevValue = value;

    // Shift all elements to the right, starting at pos
    for (int i = pos; i < array.length; i++) {
        int tmp = prevValue;
        prevValue = array[i];
        array[i] = tmp;
    }
}

int[] a = {1, 2, 3, 4, 5, 6};
addPos(a, 4, 87);
// output: {1, 2, 3, 4, 87, 5}

3
这里有一个几乎一行的代码可以实现它:
String[] prependedArray = new ArrayList<String>() {
  {
    add("newElement");
    addAll(Arrays.asList(originalArray));
  }
}.toArray(new String[0]);

2

org.apache.commons.lang3.ArrayUtils#add(T[], int, T)在最新的commons lang3中已弃用,您可以使用org.apache.commons.lang3.ArrayUtils#insert(int, T[], T...)代替。

此方法已被insert(int, T[], T...)替代,并可能在将来的版本中被删除。请注意,在新方法中,对于空输入数组的处理与旧方法不同:将X插入到空数组中会导致null而不是X

示例代码:

    Assert.assertArrayEquals
            (org.apache.commons.lang3.ArrayUtils.insert
            (4, new int[]{1, 2, 3, 4, 5, 6}, 87), new int[]{1, 2, 3, 4, 87, 5, 6});

2
请查看commons,它使用arrayCopy(),但语法更好。对于那些逐个元素代码回答的人:如果这不是作业,那么这很简单,有趣的答案是促进重用的答案。对于那些提出列表的人:可能读者也知道这一点,应该提到性能问题。请注意保留HTML标签。

1
该 add 方法已被弃用。现在必须使用 insert 方法。参数位置也已更改。https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ArrayUtils.html - Fran Marzoa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接