How to remove element from an array

后端 未结 4 495
时光取名叫无心
时光取名叫无心 2020-12-11 17:32

I have an array for example:

String [][] test = {{\"a\",\"1\"},
                    {\"b\",\"1\"},
                    {\"c\",\"1\"}};

Can

相关标签:
4条回答
  • 2020-12-11 18:20

    You cannot remove an element from an array. The size of a Java array is determined when the array is allocated, and cannot be changed. The best you can do is:

    • Assign null to the array at the relevant position; e.g.

      test[1] = null;
      

      This leaves you with the problem of dealing with the "holes" in the array where the null values are. (In some cases this is not a problem ... but in most cases it is.)

    • Create a new array with the element removed; e.g.

      String[][] tmp = new String[test.length - 1][];
      int j = 0;
      for (int i = 0; i < test.length; i++) {
          if (i != indexOfItemToRemove) {
              tmp[j++] = test[i];
          }
      }
      test = tmp;
      

      The Apache Commons ArrayUtils class has some static methods that will do this more neatly (e.g. Object[] ArrayUtils.remove(Object[], int), but the fact remains that this approach creates a new array object.

    A better approach would be to use a suitable Collection type. For instance, the ArrayList type has a method that allows you to remove the element at a given position.

    0 讨论(0)
  • 2020-12-11 18:20

    You could set the entry in the array to null (test[0][1] = null;). However, "removing" the item such that the array will have one element less than before is not doable without recreating the array. If you plan to change data in the data structure regularly an ArrayList (or another Collection class depending on your needs) might be more convenient.

    0 讨论(0)
  • 2020-12-11 18:26

    My solution is:

    You cannot remove an element from an array => it's correct, but we can do something to change current array.

    No need assign null to the array at the relevant position; e.g.
    
    test[1] = null;
    
    Create a new array with the element removed; e.g.
    
    String[][] temp = new String[test.length - 1][];
    

    Need to get index at string/array to remove: IndexToRemove

    for (int i = 0; i < test.length-1; i++) {
                    if (i<IndexToRemove){
                        temp[i]=test[i];
                    }else if (i==IndexToRemove){
                        temp[i]=test[i+1];
                    }else {
                        temp[i]=test[i+1];
                    }
    }
    test = temp;
    

    Hope it helpful!

    0 讨论(0)
  • 2020-12-11 18:32

    There is no built-in way to "remove" items from a regular Java array.

    What you want to use is an ArrayList.

    0 讨论(0)
提交回复
热议问题