欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Arrays 博客分类: java.util Arrays

程序员文章站 2024-02-25 18:04:51
...
Arrays


一、总结

1.基于 jdk 1.8

二、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 a the array by which the list will be backed
     * @return a list view of the specified array
     */
    public static <T> List<T> asList(T... a) {
	return new ArrayList<T>(a);
    }



1.参数为 T 多个泛型T
若参数为基础数据类型的数组,则将其视为一个整体,如 int [] a ,此时的size = 1
若参数为引用数据类型,则其size为数据的个数

2.ArrayList 非 java.util.ArrayList

三、Arrays.ArrayList 内部私有静态类
    /**
     * @serial include
     */
    // 继承 Abstract ,而 Abstract 实现 List ,所以 asList 才可以用 List 接收
    // 即 ArrayList 间接实现了 List
    private static class ArrayList<E> extends AbstractList<E>
    // RandomAccess 可以随机访问,Serializable 可序列化
	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;
	}
        // 以下是 ArrayList 实现的方法,无RemoveAll 方法,所以asList 的返回值List
        // 调用 removeAll时会抛出无此操作方法的异常
	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