Java increase array by X size

前端 未结 6 605
广开言路
广开言路 2021-01-27 21:04

I need an array that I can determine its size from the start and if it has no more empty spaces then increase its size by X. For example:

int arrayS         


        
6条回答
  •  长发绾君心
    2021-01-27 21:27

    ArrayList or Vector is resizing by itself, so you don't need to do it manually at all. The drawback is that they use object types, not primitives. You are encouraged to use ArrayList as Vector is deprecated.

    If you need automatically resizable primitive arrays use Apache Commons Primitives.

    If you want to resize your array manually you should allocate new array and copy data and change reference like this:

    int[] array_new = new int[size_new];
    System.arraycopy(array, 0, array_new, 0, array.length);
    array = array_new;
    

    Or use Arrays.copy() as other answers suggests.

提交回复
热议问题