Most memory efficient way to grow an array in Java?

前端 未结 12 1276
陌清茗
陌清茗 2020-12-13 19:18

I\'m not too concerned about time efficiency (the operation will be rare), but rather about memory efficiency: Can I grow the array without temporarily having all th

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 20:18

    The best way to have a dynamically resizing 'array' or list of items is to use an ArrayList.

    Java has already built in very efficient resizing algorithms into that data structure.

    But, if you must resize your own array, it is best to use System.arraycopy() or Arrays.copyOf().

    Arrays.copyOf() can most simply be used like so:

    int[] oldArr;
    int newArr = Arrays.copyOf(oldArr, oldArr.length * 2);
    

    This will give you a new array with the same elements as the old array, but now with room to spare.

    The Arrays class in general has lots of great methods for dealing with arrays.

    Also

    It is important to make sure that you aren't just growing your array by one element each time an element is added. It is best to implement some strategy where you only have to resize the array every once in a while. Resizing arrays is a costly operation.

提交回复
热议问题