JAVA:ArrayList常用方法+底层源码分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dian1pei2xiao3/article/details/84837619
 Arraylist特点:动态开辟,初始容量为10,只能放引用数据类型
ArrayList<Integer> arrayList=new ArrayList<Integer>();
 
Arraylist增加元素,自增扩容方式1.5倍,Arrays.copyof()拷贝
 可以放重复值,可以放多个null值
        arrayList.add(12);
        arrayList.add(15);
        arrayList.add(1);
        arrayList.add(null);
        arrayList.add(null);
        arrayList.add(12);
源码对于增加元素扩容方式:

  拷贝方式Array.copyof()

        private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
        }

Arrays.copyof() 与System.arraycopy()的区别:

Arrays.copyof()底层调用的是System.arraycopy()

System.arraycopy()

 public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }


public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
/**三种遍历方式:
 * 1.for循环
 * 2.增强for循环
 * 3.迭代器:有hashnext(),next()两个方法
 */
 System.out.println("for循环");
        //size()计算arrayList中存放元素的个数
        for(int i=0;i<arrayList.size();i++){
            //通过索引获取元素
            System.out.println(arrayList.get(i));

        }
        System.out.println("增强for循环");
        for (Integer value:arrayList) {
            System.out.println(value);
        }
        System.out.println("迭代器");
        Iterator<Integer> iterator = arrayList.iterator();
        while (iterator.hasNext()){
            Integer next = iterator.next();
            System.out.println(next);
        }
/**
 * 增删改查效率问题:
 * 增加:add()
 * 删:remove
 * 查:get()
 * 查询效率高
 *
 */

ArrayList与数组的区别:

1.存储数据:ArrayList只能存储引用数据类型,数组既可以存放引用数据类型也可以存放基本数据类型

2.初始化与扩容方式:

ArrayList默认初始容量为10,动态开辟,扩容方式为1.5倍,应用grow()方法,

数组必须自己定义容量大小,没有动态开辟,扩容需要自己手动扩容

3.遍历方式:

数组与ArrayList都可以用索引遍历,使用for循环和增强for循环,而ArrayList底层实现iterator()接口,可以通过迭代器遍历,应用hasNext()和Next()方法。

猜你喜欢

转载自blog.csdn.net/Dian1pei2xiao3/article/details/84837619