Arrays

Arrays

java version “1.8.0_131”

一、总结

  • 数组工具类,私有构造方法,提供静态方法
  • Arrays.asList()与相应集合的toArray()方法实现List与Array 之间的互相转化;如:ArrayList.toArray

二、源码分析

1. asList()

将数组转化为集合

    /**
     * Returns a fixed-size list backed by the specified array.  (Changes to
     * the returned list "write through" to the array.)  This method acts
     * as bridge between array-based and collection-based APIs, in
     * combination with {@link Collection#toArray}.  The returned list is
     * serializable and implements {@link RandomAccess}.
     *
     * <p>This method also provides a convenient way to create a fixed-size
     * list initialized to contain several elements:
     * <pre>
     *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");
     * </pre>
     *
     * @param <T> the class of the objects in the array
     * @param a the array by which the list will be backed
     * @return a list view of the specified array
     */
    @SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }
注释
  • 返回由指定数组支持的固定大小的List集合。
  • 将写入的array 改为返回的集合List
  • Arrays.asList() 与 Collection.toArray() 是List 与 Array 相互转化的桥梁
  • 返回值 List 实现了序列化 Serializable 与 RandomAccess 接口
  • asList 方法允许同时传入多个参数
总结
  • asList()只是将Array转为List,数组的大小、内容均为改变
  • 此处返回的ArrayList不是java.util.ArrayList,而是Arrays.ArrayList即Arrays内部的私有静态内部类。
  • T 泛型,Type , 表示Java类
问题
  • 为什么Arrays要再次实现ArrayList,而不直接使用java.util.ArrayList?
    从asList()方法的注释上得知,该方法只是将传入的Array转为List而保持内容及大小不变,即只读,不提供扩展、删除方法,所以重新定义了一个ArrayList
  • 为什么返回值可以使用List接收?因为Arrays.ArrayList 继承了 AbstractList,而 AbstractList 实现了 List 接口,即 Arrays.ArrayList间接实现了 List
  • 为什么使用泛型T而不是用Object?因为Object虽然是所有类的父类,但使用过程需伴随着类型的强制转换,如果类型没有对应上,则会抛出转化异常;使用泛型的话,在调用方法前类型就已经确认,无需进行类型转换
注意
  • 基本数据类型数据与基本数据类型的包装类的数组的区别
    // 对比基本数据类型数组、包装类数据类型数组转化后的结果
    public static void main(String[] args) {
        int [] intArray = new int[]{1,2,3,4};
        List<int[]> asList = Arrays.asList(intArray);
        System.out.println(asList.size()); // 1 

        Integer [] integerArray = new Integer[]{1,2,3,4};
        List<Integer> asList2 = Arrays.asList(integerArray);
        System.out.println(asList2.size()); // 4


    }
结果分析
  • 小技巧:快速生成方法的返回值,IDE为Eclipse,将鼠标放在方法的尾部,ctrl+1,根据提示选择第一项,assign statement to new local variable ; 或者 在方法前ctrl+2 , 再按L ;自动添加方法的返回值
  • asList()方法的参数为T 多个泛型T ,而基本数据类型不是泛型,int[] 整体作为泛型,索引参数为 基本类型数组时,asList()返回的List的长度为1
  • asList()方法的参数为包装类数组时,包装类即引用数据类型,即多个泛型作为参数,返回的list的长度为数组的length

  • asList()方法的返回值是List,实质是return new ArrayList(),此ArrayList是Arrays内部私有静态类,是为了实现 asList() 返回与传入的数组的大小相同的List而定义;不支持add()、remove()等改变数组大小的方法;但List中有这些方法,即可以调用;如果调用的话,会抛出异常 java.lang.UnsupportedOperationException。分析调用过程:
        // asList 可接收多个参数作为入参
        List<Integer> asList3 = Arrays.asList(1,2,3,4);
        // 调用list中的remove
        asList3.remove(1); 

        // 调用AbstractList 类中的 remove()
        // 因为AbstractList 实现了 List,而ArrayList继承了AbstractList
        // AbstractList中remove()定义如下
        // 由于ArrayList继承AbstractList时未重写该方法,所以List.remove 时调用父类中的方法,故抛出该异常
            /**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E remove(int index) {
    throw new UnsupportedOperationException();
    }

    // 如果想调用 add() remove() 等方法
    List<Integer> asList4 = new ArrayList<Integer>(asList3);
    asList4.remove(1);
结论
  • asList()返回值list,不可调用 add()、remove(),会抛出异常
  • 如果想调用 add()、remove(),将其作为参数放入java.util.ArrayList中

2. ArrayList

    /**
     * @serial include
     */
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        // 类的私有属性
        // E  泛型,表示集合中的元素
        // ArrayList  的底层是数组,同 java.util.ArrayList
        // 不同的是 java.util.ArrayList 中是 Object[] elementData
        // 而此处是 泛型E 的数组
        private final E[] a;

        ArrayList(E[] array) {
            // 此处调用 Objects 中判空的方法,如果 array 为空,抛出 NullPointerException
            a = Objects.requireNonNull(array);
        }

        @Override
        public int size() {
            return a.length;
        }

        @Override
        public Object[] toArray() {
            return a.clone();
        }

        @Override
        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size,
                                     (Class<? extends T[]>) a.getClass());
            System.arraycopy(this.a, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        }

        @Override
        public E get(int index) {
            return a[index];
        }

        @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }

        @Override
        public int indexOf(Object o) {
            E[] a = this.a;
            if (o == null) {
                for (int i = 0; i < a.length; i++)
                    if (a[i] == null)
                        return i;
            } else {
                for (int i = 0; i < a.length; i++)
                    if (o.equals(a[i]))
                        return i;
            }
            return -1;
        }

        @Override
        public boolean contains(Object o) {
            return indexOf(o) != -1;
        }

        @Override
        public Spliterator<E> spliterator() {
            return Spliterators.spliterator(a, Spliterator.ORDERED);
        }

        @Override
        public void forEach(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            for (E e : a) {
                action.accept(e);
            }
        }

        @Override
        public void replaceAll(UnaryOperator<E> operator) {
            Objects.requireNonNull(operator);
            E[] a = this.a;
            for (int i = 0; i < a.length; i++) {
                a[i] = operator.apply(a[i]);
            }
        }

        @Override
        public void sort(Comparator<? super E> c) {
            Arrays.sort(a, c);
        }
    }
  • 私有的内部静态类
  • 继承 AbstractList ,作用:实现了List接口,减少子类在实现List接口需要实现的方法的数量
  • 实现 RandomAccess ,作用:标识该集合为顺序表,遍历时最好使用for循环遍历,相对应的,如果是LinkedList,遍历时最好使用 iterator 迭代器方式;在大量数据的集合时性能最优
  • 实现 java.io.Serializable ,作用:类声明的对象可序列化为一个字节序列,保存对象的状态
  • E 泛型,Element ,代表集合中的元素
Arrays.ArrayList 与 java.util.ArrayList的异同
  • 数据结构均为数组,前者是 E[] 泛型数组;后者为 Object[] 类型数组;前者使用时无需进行数据类型的转换
  • 构造方法:若参数为null,前者若泛型集合为null,抛出NPE(null point exception);后者同样会抛出异常,elementData = c.toArray(); 时抛出 NPE异常。
        /**
         * Arrays.ArrayList 构造方法抛出空指针示例
         */

        Integer [] integerArray4 = null;
        // 此处抛出NPE异常
        List<Integer> asList6 = Arrays.asList(integerArray4);
        System.out.println(asList6);

        int [] intArray1 = null ;
        // 此处运行正常
        // 原因:int [] 整体作为泛型,null 为 E[] 中的元素,非空
        List<int[]> asList5 = Arrays.asList(intArray1);
        System.out.println(asList5); // 输出 [null]

3.copyOf()

    /**
     * Copies the specified array, truncating or padding with nulls (if necessary)
     * so the copy has the specified length.  For all indices that are
     * valid in both the original array and the copy, the two arrays will
     * contain identical values.  For any indices that are valid in the
     * copy but not the original, the copy will contain <tt>null</tt>.
     * Such indices will exist if and only if the specified length
     * is greater than that of the original array.
     * The resulting array is of exactly the same class as the original array.
     *
     * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @return a copy of the original array, truncated or padded with nulls
     *     to obtain the specified length
     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @since 1.6
     */
    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }

    /**
     * Copies the specified array, truncating or padding with nulls (if necessary)
     * so the copy has the specified length.  For all indices that are
     * valid in both the original array and the copy, the two arrays will
     * contain identical values.  For any indices that are valid in the
     * copy but not the original, the copy will contain <tt>null</tt>.
     * Such indices will exist if and only if the specified length
     * is greater than that of the original array.
     * The resulting array is of the class <tt>newType</tt>.
     *
     * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @param newType the class of the copy to be returned
     * @return a copy of the original array, truncated or padded with nulls
     *     to obtain the specified length
     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @throws ArrayStoreException if an element copied from
     *     <tt>original</tt> is not of a runtime type that can be stored in
     *     an array of class <tt>newType</tt>
     * @since 1.6
     */
    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        // 判断新的数据类型是否是Object[]
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) 
        // 若不是Object[]类型重新生成一个新的数组,类型为T            Array.newInstance(newType.getComponentType(), newLength);
        // 调用System 中的Native 方法进行数组copy
        // 从 original 的 0 位置开始,向 copy 的 0 位置,复制元素,长度为 新旧数组的最小长度
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值