What is the default initialization of an array in Java?

后端 未结 7 823
我在风中等你
我在风中等你 2020-11-22 16:30

So I\'m declaring and initializing an int array:

static final int UN = 0;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
    arr[i] = UN;
}
<         


        
7条回答
  •  渐次进展
    2020-11-22 16:41

    Java says that the default length of a JAVA array at the time of initialization will be 10.

    private static final int DEFAULT_CAPACITY = 10;
    

    But the size() method returns the number of inserted elements in the array, and since at the time of initialization, if you have not inserted any element in the array, it will return zero.

    private int size;
    
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,size - index);
        elementData[index] = element;
        size++;
    }
    

提交回复
热议问题