public ArrayList(Collection<? extends E> c)方法的一个注释 c.toArray might (incorrectly) not return Objec...

本文深入探讨了Java中ArrayList构造函数的实现原理,特别是通过集合类对象进行初始化的过程,并解析了一个可能引发误解的注释,同时提供了测试代码示例。
/**
 * Constructs a list containing the elements of the specified
 * collection, in the order they are returned by the collection's
 * iterator.
 * 使用集合类对象初始化ArrayList
 *
 * @param c the collection whose elements are to be placed into this list
 * @throws NullPointerException if the specified collection is null
 */
public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    size = elementData.length;
    //刚才看了一眼这个toArray方法,确实有时候返回的不是Obdect[],
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, size, Object[].class);
}

 


以上为ArrayList的一个构造函数,在里面有一句
c.toArray might (incorrectly) not return Object[] (see 6260652)
这个注释,参见bug6260652,java的bug官网http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6260652


问题就在这儿了,List<String> strList= Arrays.asList("abc");返回的结果是String[],不谢。。。

以下为测试代码

1   public static void main(String[] args) {
2         List<String> stringList= Arrays.asList("test");
3         Object[] strList=stringList.toArray();
4         System.out.println(strList.getClass());
5     }

 

结果如下:

 

转载于:https://www.cnblogs.com/akgang/p/6734160.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值