ArrayList经常使用方法

ArrayList总结

  1. ArrayList 其实是经过一个数组去保存数据的。当咱们构造ArrayList时;若使用默认构造函数,则ArrayList的默认容量大小是10。
  2. 当ArrayList容量不足以容纳所有元素时,ArrayList会从新设置容量:新的容量=“(原始容量x3)/2 + 1”。
  3. ArrayList的克隆函数,便是将所有元素克隆到一个数组中。
  4. ArrayList实现java.io.Serializable的方式。当写入到输出流时,先写入“容量”,再依次写入“每个元素”;当读出输入流时,先读取“容量”,再依次读取“每个元素”

经常使用方法(基于源码分析)

向集合中添加元素:

  • arrayList.add(); —————— 加入一个元素(Object)java

  • arrayLIst.addAll(); —————— 加入集合元素(Collection)web

/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */
    public boolean add(E e) {
        modCount++;
        add(e, elementData, size);
        return true;
    }
  • arrayList.add(index, element);—————在指定位置添加元素>数组

public void add(int index, E element) {
        rangeCheckForAdd(index);
        modCount++;
        final int s;
        Object[] elementData;
        if ((s = size) == (elementData = this.elementData).length)
            elementData = grow();
        System.arraycopy(elementData, index,
                         elementData, index + 1,
                         s - index);
        elementData[index] = element;
        size = s + 1;
    }

删除集合中的元素:

  • arrayList.remove();app

/** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */
    public E remove(int index) {
        Objects.checkIndex(index, size);
        final Object[] es = elementData;

        @SuppressWarnings("unchecked") E oldValue = (E) es[index];
        fastRemove(es, index);

        return oldValue;
    }

替换集合中的元素:

  • arrayList.set(index, element);svg

public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

输出ArrayList集合的长度:

  • arrayList.size();函数

查看某元素在集合中的下标:

  • arrayLIst.indexOf(); —————— 从前日后查找源码分析

public int indexOf(Object o) {
            int index = root.indexOfRange(o, offset, offset + size);
            checkForComodification();
            return index >= 0 ? index - offset : -1;
        }
  • arrayList.lastIndexOf(); —————— 从后向前查找测试

public int lastIndexOf(Object o) {
        int index = root.lastIndexOfRange(o, offset, offset + size);
        checkForComodification();
        return index >= 0 ? index - offset : -1;
 }

判断ArrayList集合中是否包含某个元素:

  • arrayList.contains();this

public boolean contains(Object o) {
            return indexOf(o) >= 0;
        }

截取下标1-3(不包括3)的子集合:

  • arrayList.subList(1, 3);spa

public List<E> subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new SubList<>(this, fromIndex, toIndex);
        }
*******************************************************************************
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    }

集合的遍历:

  1. for循环遍历
for(int i = 0; i < arrayList.size(); i++) {
			System.out.println(arrayList.get(i));
		}
  1. 经过foreach循环来遍历
for(Object o:arrayList) {
			System.out.println(o);
		}
  1. 经过迭代器来遍历 Iterator
Iterator iterator = arrayList.iterator();
	while(iterator.hasNext()) {
		System.out.println(iterator.next());
	}

遍历ArrayList时,使用随机访问 (即,经过索引序号访问 ) 效率最高,而使用迭代器的效率最低!


ArrayList示例:

import java.util.*;

/* * @desc ArrayList经常使用API的测试程序 * @author 端脑 */
public class ArrayListTest {

    public static void main(String[] args) {
        
        // 建立ArrayList
        ArrayList list = new ArrayList();

        // 将“”
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        // 将下面的元素添加到第1个位置
        list.add(0, "5");

        // 获取第1个元素
        System.out.println("the first element is: "+ list.get(0));
        // 删除“3”
        list.remove("3");
        // 获取ArrayList的大小
        System.out.println("Arraylist size=: "+ list.size());
        // 判断list中是否包含"3"
        System.out.println("ArrayList contains 3 is: "+ list.contains(3));
        // 设置第2个元素为10
        list.set(1, "10");

        // 经过Iterator遍历ArrayList
        for(Iterator iter = list.iterator(); iter.hasNext(); ) {
            System.out.println("next is: "+ iter.next());
        }

        // 将ArrayList转换为数组
        String[] arr = (String[])list.toArray(new String[0]);
        for (String str:arr)
            System.out.println("str: "+ str);

        // 清空ArrayList
        list.clear();
        // 判断ArrayList是否为空
        System.out.println("ArrayList is empty: "+ list.isEmpty());
    }
}

返回ArrayList目录