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

博客探讨了Arrays.asList方法的参数要求,通过分析源码指出输入数组中对象的class类型影响方法行为。代码示例展示了特定情况下,数组类型的层级与入参类型的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录

看代码

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}.
     *
     * <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);
    }

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值