ArrayList、LinkedList、 Vector、Map 用法比较
ArrayList 和 Vector 是采用数组方式存储数据,此数组元素总数大于实际存储的数据个数以便增加
和插入元素,二者都允许直接序号索引元素,但是插入数据要移动数组元素等内存操作,所以它们索
引数据快、插入数据慢。
ArrayList 数组存储方式:
[java] view plaincopyprint?
1 private transient Object[] elementData;
2 public ArrayList(int initialCapacity) {
3 super();
4 if (initialCapacity < 0)
5 throw new IllegalArgumentException("Illegal Capacity: " +
initialCapacity);
6 this.elementData = new Object[initialCapacity];
7 }
8
9 // 空构造函数,默认容量大小为10
10 public ArrayList() {
11 this(10);
12 }
13
14 public ArrayList(Collection<? extends E> c) {
15 elementData = c.toArray();
16 size = elementData.length;
17 // c.toArray might (incorrectly) not return Object[] (see 6260652)
18 if (elementData.getClass() != Object[].class)
19 elementData = Arrays.copyOf(elementData, size, Object[].class);
20 }
Vector 由于使用了 synchronized 同步方法(如 add、insert、remove、set、equals、hashcode
等操作),因此是线程安全,性能上比 ArrayList 要差。
Vector 数组存储方式:
[java] view plaincopyprint?