Arrays.asList的入参不同-小知识点

文章目录

    • 看代码
    • 原因

看代码

public class TestArrays {
    public static void main(String[] args) {
        Character[] array = new Character[]{'h','e','l','l','o'};

        char[] charArray = new char[]{'h','e','l','l','o'};


        List<Character> list1 = Arrays.asList(array);
        list1.forEach(System.out::println);


        List<char[]> list2 = Arrays.asList(charArray);
        list2.forEach(System.out::println);
    }
}

预测以上代码的输出结果是啥?

结果:

h
e
l
l
o
hello

原因

先来看一下Arrays.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}.
     *
     * 

This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: *

     *     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
     * 
* * @param 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); }

看其中入参要求the class of the objects in the array,即在数组中的objects的class类型。

此时再来看上述的代码,其中Character[]的数组中的对象的class类型为Character,而char[]的数组本身就是一个对象,里面再没有class类型了,所以这个时候入参的T类型就是char[]

你可能感兴趣的:(java)