1.构造函数
无参的构造函数!
该无参的构造函数,默认构造默认容量为10的空数组
即:一个new ArrayList的时候,不管用不用都会占用10单位的空间
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
有参的构造函数
以集合为参数的构造函数
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();//将继承集合接口的类变成数组,
if ((size = elementData.length) != 0) {//如果出现了上面的bug,那么久执行下面的操作
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
内部的bug处理机制:
// c.toArray might (incorrectly) not return Object[] (see 6260652)
当同时传入父类数组接受子类数组的引用时,同时存入子类与父类对象时;此时获取数组的getClass则会报错
Exception in thread "main" java.lang.ArrayStoreException:
public class App
{
public static void main( String[] args )
{
AppSon[] b = new AppSon[3];
App[] apps = b;
apps[0] = new AppSon();
apps[1] = new App();
Class<? extends App[]> aClass = apps.getClass();
System.out.println(aClass);
}
}
class AppSon extends App{}
trimToSize方法主要是通过校验size(实际大小,存有元素数量的大小) 与已开辟的空间做对比进行;然后减少将elementData多余的空间删除。【这个方法主要是节省了内存】
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
* @param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
754行