ArrayList

  • 构造方法

  • 构造方法可以指定大小
public ArrayList(int initialCapacity) 

  • 无参构造方法初始化是默认大小为  10
public ArrayList() {
    this(10);
    } 
注意,此实现不是同步的。如果多个线程同时访问一个 ArrayList 实例,而其中至少一个线程从结构上修改了列表,那么它必须 保持外部同步。(结构上的修改是指任何添加或删除一个或多个元素的操作,或者显式调整底层数组的大小;仅仅设置元素的值不是结构上的修改。)这一般通过对自然封装该列表的对象进行同步操作来完成。如果不存在这样的对象,则应该使用 Collections.synchronizedList 方法将该列表“包装”起来。这最好在创建时完成,以防止意外对列表进行不同步的访问:
List list = Collections.synchronizedList(new ArrayList(...)); 

在添加大量元素前,应用程序可以使用 ensureCapacity 操作来增加 ArrayList 实例的容量。这可以减少递增式再分配的数量  old*1.5+1 的增量
 public void ensureCapacity(int minCapacity) {
    modCount++;
    int oldCapacity = elementData.length;
    if (minCapacity > oldCapacity) {
        Object oldData[] = elementData;
        int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
        newCapacity = minCapacity;
        elementData = (E[])new Object[newCapacity];
        System.arraycopy(oldData, 0, elementData, 0, size);
    }
    } 
 

方法

  • 判断是否为空
 public boolean isEmpty() {
    return size == 0;
    }  
  • 增加元素,会自动增加容量
 public boolean add(E o) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = o;
    return true;
    } 
  • 在指定索引处增加
 public void add(int index, E element) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);
    ensureCapacity(size+1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
             size - index);
    elementData[index] = element;
    size++;
    } 
  • 删除,null 赋值给对象,垃圾回收
public E remove(int index) 
elementData[--size] = null// Let gc do its work 
  • 清空list
  public void clear() {
    modCount++;
    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;
    size = 0;
    }  
  •  添加集合
  public boolean addAll(Collection<? extends E> c)
  1. List<String> list = Collections.synchronizedList(new ArrayList<String>(1));
  2. list.add("111");
  3. list.add("222");
  4. list.add("222");
  5. list.add(0,"101");
  6. List<String> list2 = Collections.synchronizedList(new ArrayList<String>());
  7. list2.add("444");
  8. //add collection
  9. list2.addAll(list);
  10. System.out.println(list2);
  11. //output [444, 101, 111, 222, 222]







原文地址:https://www.cnblogs.com/liubo6/p/4491164.html