为什么在 java.util.Arrays 中有一个 ArrayList 声明 [英] Why is there an ArrayList declaration within java.util.Arrays

查看:28
本文介绍了为什么在 java.util.Arrays 中有一个 ArrayList 声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JDK 1.7 中,asList 使用了一个 ArrayList 声明.

In JDK 1.7, there is an ArrayList declaration which is used by asList.

他们为什么要创建一个新的私有静态类而不使用java.util.ArrayList:

Why did they make a new private static class and not use java.util.ArrayList:

@SafeVarargs
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}

/**
 * @serial include
 */
private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, java.io.Serializable
{
    private static final long serialVersionUID = -2764017481108945198L;
    private final E[] a;

    ArrayList(E[] array) {
        if (array==null)
            throw new NullPointerException();
        a = array;
    }

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

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

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

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

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

    public int indexOf(Object o) {
        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;
    }

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

推荐答案

因为Arrays.asList() 由给定的数组支持.它包装了那个数组;对数组的更改反映在 List 中,反之亦然.

Because the List returned by Arrays.asList() is backed by the given array. It wraps that array; changes to the array are reflected in the List and vice versa.

此外,因此,此处返回的 List 具有固定大小.因此,它不能是 ArrayList,因为 ArrayList 可以增长或缩小.

Also, as a result of this, the List returned here has a fixed size. So, it can't be an ArrayList because ArrayList can grow or shrink.

这篇关于为什么在 java.util.Arrays 中有一个 ArrayList 声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆