结论:初始定义的只是ArrayList的容量,而ArrayList的set方法中判断的是实际元素的个数,所以会报错
过程:
当我们定义一个初始化大小的ArrayList,直接调用set方法会报下标越界异常
这是用暴力解法做一道算法题时写的代码
public static List<Integer> countSmaller(int[] nums){
int len = nums.length;
List<Integer> counts = new ArrayList<Integer>(len);
for(int i = 0;i<len;i++){
int currCount = 0;
for(int j = i+1;j<len;j++){
if(nums[j]<nums[i]){
currCount++;
}
}
counts.set(i,currCount);
}
return counts;
}
public static void main(String[] args) {
int[] test = new int[]{5,2,6,1};
System.out.println(countSmaller(test));
}
运行异常
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.set(ArrayList.java:448)
at DesignPartten.LengthOfLIS.countSmaller(LengthOfLIS.java:19)
at DesignPartten.LengthOfLIS.main(LengthOfLIS.java:28)
ArrayList有参构造方法源码
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
调用的时候只是声明了一个Object数组并赋值给elementData
set方法源码
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
会调用一个rangeCheck方法检查是否越界
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
而我们当前的ArrayList实例的size并没有设置,默认为0;抛出越界异常。
解决:使用add方法从数组下标0开始添加元素,不能跳跃下标添加。
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++;
}