JAVA面试题整理 || ArrayList源码分析

本文详细分析了ArrayList的创建、add方法、remove方法以及其他关键操作的源码,强调其非线程安全特性及扩容机制。在ArrayList的add方法中,首次添加元素时容量会扩容至10,后续根据需要按一定比例扩容。同时,文章提醒在大集合中避免使用add(int index, E element)方法以防止效率问题。最后,提供了面试总结和读者福利,包括Java面试题和学习资料。" 107266846,9329892,边缘计算:分离内核与虚拟机保障关键任务安全,"['边缘计算', '虚拟化', '安全技术', '实时操作系统', '嵌入式系统']
摘要由CSDN通过智能技术生成

ArrayList创建和add等各种api使用原理

  • ArrayList 允许空值和重复元素,当往 ArrayList 中添加的元素数量大于其底层数组容量时,其会通过 扩容 机制重新生成一个更大的数组。
  • ArrayList 是非线程安全类,并发环境下,多个线程同时操作 ArrayList,会引发不可预知的异常或错误。
    (文章中有超级福利)

ArrayList创建源码

  • 带有初始容量的构造方法
// Shared empty array instance used for empty instances.
private static final Object[] EMPTY_ELEMENTDATA = {
   };

/**
 * Constructs an empty list with the specified initial capacity.
 * @param  initialCapacity  the initial capacity of the list
 * @throws IllegalArgumentException if the specified initial capacity
 *         is negative
 */
public ArrayList(int initialCapacity) {
   
    // 参数大于0,elementData初始化为initialCapacity大小的数组,即根据传入的参数大小创建数组
    if (initialCapacity > 0) {
   
        this.elementData = new Object\[initialCapacity\];
    // 参数等于0,创建空数组
    } else if (initialCapacity == 0) {
   
        this.elementData = EMPTY_ELEMENTDATA;
    // 否则抛出异常,参数异常,初始化容量异常
    } else {
   
	throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); 
    }
}
  • 无参构造方法,即使用默认的size为10的空数组,

在构造方法中没有对数组长度进行设置,会在后续调用add方法的时候进行扩容

/** 
 * Shared empty array instance used for default sized empty instances. We
 * distinguish this from EMPTY\_ELEMENTDATA to know how much to inflate when
 * first element is added. 
 */ 
private static final Object[] DEFAULTCAPACITY\_EMPTY_ELEMENTDATA = {
   };


/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
   
    this.elementData = DEFAULTCAPACITY\_EMPTY\_ELEMENTDATA;
}
  • 参数为集合的构造方法,将一个参数为Collection的集合转变为ArrayList(实际上就是将集合中的元素换为了数组的形式)。
/**
 * Constructs a list containing the elements of the specified
 * collection, in the order they are returned by the collection's
 * iterator.
 *
 * @param c the collection whose elements are to be placed into this list 
 * @throws NullPointerException if the specified collection is null
 */
 public ArrayList(Collection<? extends E> c) {
   
    // 如果传入的集合为空,则c.toArray()抛出空指针异常
    elementData = c.toArray();
    // 如果传入的数组容量不为0 而且toArray之后不为对象数组的话,就通过数组复制修改为底层结构是对象数组的集合
    if ((size = elementData.length) != 0) {
   
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    if (elementData.getClass()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值