arrayList分析:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
实现了泛型
RandomAccess是一个标记接口,接口内没有定义任何内容。
通过实现 java.io.Serializable 接口以启用其序列化功能。
private transient Object[] elementData;
private int size;
elementData:是元素,size为大小
transient:JAVA关键字,用transient声明的域,不会被Serializable序列化。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
这个关键在于ensureCapacityInternal方法,方法代码如下,保证超过当前容量再进行扩容:
private void ensureCapacityInternal(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
============================================================================================================
多线程测试:
public class ArrayListTest{
public static void main(String args[]) throws InterruptedException {
//List<String> v = new ArrayList<String>();
List<String> v = (List<String>) Collections.synchronizedList(new ArrayList<String>());
Thread4Collection hello1 = new Thread4Collection("hello1", v);
Thread4Collection hello2 = new Thread4Collection("hello2", v);
Thread4Collection hello3 = new Thread4Collection("hello3", v);
Thread h1 = new Thread(hello1);
Thread h2 = new Thread(hello2);
Thread h3 = new Thread(hello3);
h1.start();
h2.start();
h3.start();
}
}
public class Thread4Collection extends Thread{
String name;
List<String> v;
int a = 5;
public Thread4Collection(String name, List<String> v) {
this.name = name;
this.v = v;
}
public void run() {
this.test();
}
public void test(){
System.out.println(name + "start");
while (a <10) {
v.add(name + ".add");
System.out.println(name + " list size is " + v.size());
System.out.println(name + " list is " + v);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
a++;
}
}
}
List<String> v = (List<String>) Collections.synchronizedList(new ArrayList<String>());
可以使arrayList实现同步,保证线程安全
System类arrayCopy方法测试
public static void main(String[] args) {
//System.console();
int[] ids = { 1, 2, 3, 4, 5 };
System.out.println(Arrays.toString(ids));
//测试自我复制
//把从索引0开始的2个数字复制到索引为3的位置上
System.arraycopy(ids, 0, ids, 3, 2);
System.out.println(Arrays.toString(ids)); // [1, 2, 3, 1, 2]
//复制到另一个数组中
int[] ids2 = new int[ids.length];
System.arraycopy(ids, 0, ids2, 0, ids.length);
System.out.println(Arrays.toString(ids2));
}