How to add an element at the end of an array?

前端 未结 6 1635
迷失自我
迷失自我 2021-01-02 10:33

I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don\'t know

6条回答
  •  离开以前
    2021-01-02 11:05

    To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).

    What you can do is create a new array one element larger and fill in the new element in the last slot:

    public static int[] append(int[] array, int value) {
         int[] result = Arrays.copyOf(array, array.length + 1);
         result[result.length - 1] = value;
         return result;
    }
    

    This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.

    One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.

    And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.

提交回复
热议问题