【问题标题】:Java - Adding element at specific index and pushing other elements downJava - 在特定索引处添加元素并向下推其他元素
【发布时间】:2013-11-13 14:24:47
【问题描述】:

此功能应该在所选索引处添加一个元素,并将数组元素中的所有其他元素向下推。因此,例如,假设我有以下数组:

[0] = zero
[1] = one
[2] = two

如果我在索引 0 处添加另一个名为 NEWZERO 的元素,则数组必须如下所示:

[0] = NEWZERO
[1] = zero 
[2] = one 
[3] = two

但目前我遇到了 IndexOutOfBounds 异常并且它不起作用。

附:我不想使用内置的 ArrayList 库,它会自动为您完成。

    public void insert(int i, String s) {

    if (array[i] == null) {
        array[i] = s; //Need to add feature that instantly puts the element at the first available spot on the list.
    } else { 
        for (int j = i; j < array.length; j++) { //Can't use >= i
            array[j + 1] = array[j];

            if (j == array.length - 1) { 
                break;
            } 
        }
        array[i] = s;

【问题讨论】:

  • 你需要扩大你的数组以避免异常:检查 stackoverflow.com/questions/8438879/expanding-an-array>

标签: java arrays oop


【解决方案1】:

试试这个

public void insert(int i, String s) {

    String[] newArr = new String[array.length + 1];
    for (int j = 0; j < array.length; j++) { 
        if(j < i){
           newArr[j] = array[j];
        } else if(j == i){ // '==' insted of '='
           newArr[j] = s;
        } else {
           newArr[j+1] = array[i];
        }
    }

    array = newArr;
}

【讨论】:

  • 这将是一个很大的性能损失,因为在每次插入时都会分配一个新数组。更好的选择是使用 ArrayList 而不是重新发明轮子。
  • 是的,我知道,但是“P.S. 我不想使用内置的 ArrayList 库,它会自动为您完成。”
【解决方案2】:

好吧,数组不是动态的,所以如果你有一个大小为 3 的数组,你不能向它添加任何东西,除非你创建一个大小为 oldArray.length+1 的新数组,然后用新数据填充它。

【讨论】:

    【解决方案3】:
    public static int[] addAtIndex(int[] a, int index, int value) {
     int[] newArr = new int[a.length + 1];
     int temp;
     for (int j = 0; j < a.length + 1; j++) {
      if (j < index) {
       newArr[j] = a[j];
      } else if (j == index) {
       //copy value at index to temp so that value added at specific index can be shifted right
       temp = a[j];
       newArr[j] = value;
       newArr[j + 1] = temp;
      } else {
       newArr[j] = a[index];
       index++;
      }
     }
     return newArr;
    }
    

    【讨论】:

    • 在特定索引处添加元素并右移其他元素。
    • 很好的回答!如果您在答案中添加一个小注释来解释您的代码,您真的可以提高答案的质量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    相关资源
    最近更新 更多