Arralist的3坑

1.Arrays.asList返回的并非是真正的Arraylist

//此处返回的ArrayList 是Arrays类的一个内部类,并非是 java.util包下Arraylist
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}

//该类与util包下的都是继承 AbstractList<E>,但并为重写add,remove方法,而AbstractList<E>方法中的add,remove只会抛异常
public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

2 Arraylist.subList()方法返回的List<E>并不能强转为Arraylist,add,remove操作的数据都是原始的Arraylist

List<String> stringList = new ArrayList<>();
stringList.add("大");
stringList.add("神");
stringList.add("不");
stringList.add("在");
//此处的强转会抛 java.util.ArrayList$SubList cannot be cast to java.util.ArrayList
List<String> subList = (ArrayList) stringList.subList(0, 2);

//add,remove操作原Arraylist的原因,parent.add
public void add(int index, E e) {
            if (index < 0 || index > this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
            parent.add(parentOffset + index, e);
            this.modCount = parent.modCount;
            this.size++;
        }

3.Arraylist.subList ()返回的List<String>在原数据改变后,不能进行add,remove,遍历操作

private void checkForComodification() {
    if (ArrayList.this.modCount != this.modCount)
       throw new ConcurrentModificationException();
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值