How to remove element from an array

后端 未结 4 497
时光取名叫无心
时光取名叫无心 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.

提交回复
热议问题