如何在不从列表中删除任何项目的情况下在数组中添加项目?

时间:2017-12-11 16:36:04

标签: java arrays

我有一个数组,我想在这个数组的第二个索引处添加一个新元素,但不删除列表中的任何其他项。

Current array: 
["AA", "BB", "CC", "DD"]

在第二位插入11后。

New Array:
["AA", "11", "BB", "CC", "DD"]

这就是我正在做的事情,但它消除了数组中的最后一条记录。

   private void inserItem(int pos, String value) {
        String[] result = new String[itemsArray.length];
        for(int i = 0; i < pos; i++)
            result[i] = itemsArray[i];

        result[pos] = value;
        for(int i = pos + 1; i < itemsArray.length; i++)
            result[i] = itemsArray[i-1];

        itemsArray= result;
 }

这是它给我的输出;当我使用上述方法insertItem(1,"11")

 ["AA", "11", "BB", "CC"]

6 个答案:

答案 0 :(得分:1)

创建后无法更改数组的大小。

您应该使用LinkedList<String>及其add(int index, E element)方法:

  

public void add(int index,E element)在指定的元素处插入   此列表中的指定位置。移动当前的元素   该位置(如果有的话)和右边的任何后续元素(添加   一个到他们的指数)。

String[] array = {"AA", "BB", "CC", "DD"};
LinkedList<String> list = new LinkedList<>(Arrays.asList(array));
list.add(1, "11");

请注意,您应该使用LinkedList而不是ArrayList,因为使用ArrayList进行移位的添加操作会更加昂贵。

另一件需要考虑的事情是我只使用数组来初始填充LinkedList。我不建议您每次要插入项目时都应该这样做。你应该完全停止使用数组,只需使用LinkedList。

答案 1 :(得分:0)

从技术上讲,你要添加一个元素,如果 旧数组有3个元素,你想添加1个元素,所以你应该让你新的大小为4的数组尚未完成.... Try String result [] = new String [itemsArray.length + 1] 这可能会解决您的问题

你可以简单地使用ArrayList来解决你所有的问题......

快乐编码:)

答案 2 :(得分:0)

新数组将比当前项目多一个项目:

String[] result = new String[itemsArray.length + 1];

答案 3 :(得分:0)

两个错误

private void inserItem(int pos, String value) {
    String[] result = new String[itemsArray.length + 1];//new array with old size+1
    for(int i = 0; i < pos; i++)
        result[i] = itemsArray[i];

    result[pos] = value;
    for(int i = pos + 1; i < result.length; i++)//change loop termination
        result[i] = itemsArray[i-1];

    itemsArray= result;
}

答案 4 :(得分:0)

sed '
/.*ERROR] \[/!d                     # get the line with ERROR
s///                                # delete all from start to ID
:A
/=get$/!{N;bA}                      # if the line not end with =get; get one more
s/\([^]]*\)[^:]*: \(.*\)/\1 "\2"/   # remove Get: and add "
s/\n//g                             # remove \n
s/&/_&_/g                           # replace & by _&_
' infile

答案 5 :(得分:0)

在函数内创建新数组时,使用(当前长度+ 1)创建它。我在下面编辑了你的代码。

private void insertItem(int pos, String value) {
        String[] result = new String[itemsArray.length + 1];
        for(int i = 0; i < pos; i++)
            result[i] = itemsArray[i];

        result[pos] = value;
        for(int i = pos + 1; i < itemsArray.length + 1; i++)
            result[i] = itemsArray[i-1];

        itemsArray= result;
 }

但请注意,您在此处所做的并不是扩展原始阵列。而是从原始数组的值和新添加的元素创建一个新数组。