作者:菜蔸蔸 | 来源:互联网 | 2023-09-17 14:38
1空参构造默认空容量的数值privatestaticfinalObject[]DEFAULTCAPACITY_EMPTY_ELEMENTDATA{};真正存储数据的容器Obj
1 空参构造
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData;
public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
2 有参构造
private static final Object[] EMPTY_ELEMENTDATA = {};
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);}
}
3 有参构造(传集合)
public ArrayList(Collection<? extends E> c) {Object[] a &#61; c.toArray();if ((size &#61; a.length) !&#61; 0) {if (c.getClass() &#61;&#61; ArrayList.class) {elementData &#61; a;} else {elementData &#61; Arrays.copyOf(a, size, Object[].class);}} else {elementData &#61; EMPTY_ELEMENTDATA;}
}
public Object[] toArray() {return Arrays.copyOf(elementData, size);
}
public static <T> T[] copyOf(T[] original, int newLength) {return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {&#64;SuppressWarnings("unchecked")T[] copy &#61; ((Object)newType &#61;&#61; (Object)Object[].class)? (T[]) new Object[newLength]: (T[]) Array.newInstance(newType.getComponentType(), newLength);System.arraycopy(original, 0, copy, 0,Math.min(original.length, newLength));return copy;
}
这个构造方法和clone类似 也存在“浅拷贝”的问题
集合的clone方法 调用了Arrays的copyOf 这个方法最底层做复制的实现是 System.arraycopy()
复制一维数组没问题&#xff0c;普通变量没问题 如果是二维数组或对象 就会影响原来的值
带集合的构造方法 是用了toArray方法 这个方法调用Arrays的copyOf 所以最后还是 System.arraycopy()
数组复制时 使用Arrays.copyOf和clone&#xff08;&#xff09;方法 都是一样的效果