ArrayList常用方法

ArrayList总结

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

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

向集合中添加元素:
  • arrayList.add(); —————— 加入一个元素(Object)

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

/**
  * 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();

/**
  * 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);

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();

public boolean contains(Object o) {
            return indexOf(o) >= 0;
        }
截取下标1-3(不包括3)的子集合:
  • arrayList.subList(1, 3);

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());
    }
}

看到这里,如果感兴趣的话,加微cr13219748239,白嫖全栈学习资料资料。


返回ArrayList目录

  • 11
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值