当创建数组:ArrayList<String > list=new ArrayList();
往数组里面添加数据后,数组的长度为什么能够固定,
而和集合的容量无关:例如
public static void main(String[] args) {
ArrayList<String > list=new ArrayList();
System.out.println(list);
list.add("a");
list.add("b");
System.out.println(list.get(3));
这个时候或出现异常:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
为什么这个时候的数组和集合容量不相通,数组的长度是2,不能用集合的容量来判断说
System.out.println(list.get(3));输出是null
你是怎么理解的,索引位置都不存在,肯定报错了,怎么可能返回空或者0呢?
不管是集合还是数组,你找不到下标肯定是包下标越界之类错误.
还有如上面说的,数组的下标是从0开始的.
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
// 判断是否越界 3>2 抛异常
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
有兴趣可以看看源码,get()方法在取数据之前,先调用了rangeCheck()来防止越界
你添加list只添加了两个数据 没有三个你获取不到 list的是长度 size 1开始 数组0开始