Java increase array by X size

前端 未结 6 501
广开言路
广开言路 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:20

    The only way to do this is by creating new array and copying data. However it is suggested that you use ArrayList instead.

    0 讨论(0)
  • 2021-01-27 21:21

    either use "System.arraycopy" or use ArrayList for achieving your variable size goal

    0 讨论(0)
  • 2021-01-27 21:26

    You can use Arrays.copyOf :

    intArray = Arrays.copyOf(intArray, intArray.length + additional);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-27 21:32

    I think ArrayList is better in this case instead of simple arrays because automatically grows. From the javadoc:

    Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

    But if you have to use arrays, Arrays utility class comes to your aid

    intArray = Arrays.copyOf(intArray, intArray.length + x);
    
    0 讨论(0)
  • 2021-01-27 21:33

    You cannot expand an array in Java. Once it is created, its size is fixed.

    With ArrayList this is not a problem at all, since it expands automatically to fit new elements as you .add() them.

    If you insist on using arrays anyway, you can use that:

    intArray = Arrays.copyOf(intArray, newLength);
    

    But use ArrayList if you don't have a specific need for arrays. You can use .toArray() on it to turn it into an array as well; note however that if this is an array of integers you'll have to use an Integer[] -- there is unfortunately no method in the JDK which returns an int[] from an Iterable<Integer>, and that is a pity. Guava has such a method, use Guava.

    NOTE: don't use Vector if you can help it; this class is completely obsolete in new code. Some parts of the JDK still use it for compatibility reasons, but that's about it. If you need concurrency, there is much better, for instance CopyOnWriteArrayList.

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