java容器 - 提醒1则

1、Arrays.asList()返回的List的实现类为java.util.ArrayList.ArrayList(私有内部类),固定大小,不能做add,remove操作

 

2、调用此构造方法ArrayList(Collection c) 

new ArrayList(Arrays.asList(str));对str数组的改变不影响产生的新ArrayList

原因:

JDK源码:

    public ArrayList(Collection<? extends E> c) {
                // 调用了toArray()
	elementData = c.toArray();
	size = elementData.length;
	// c.toArray might (incorrectly) not return Object[] (see 6260652)
	if (elementData.getClass() != Object[].class)
	    elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

 而toArray()注释中提到:此方法必须重新分配一个数组,尽管这个Collection背后就是一个数组

    /**
     * Returns an array containing all of the elements in this collection.
     * If this collection makes any guarantees as to what order its elements
     * are returned by its iterator, this method must return the elements in
     * the same order.
     *
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this collection.  (In other words, this method must
     * allocate a new array even if this collection is backed by an array).
     * The caller is thus free to modify the returned array.
     *
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this collection
     */
    Object[] toArray();

  所以调用以上构造方法产生的ArrayList和原先的数组,实际操纵的是2组不同的对象引用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值