java 使用subList痛徹心扉的領悟

背景

  剛開始截取List集合時使用笨的方法自己截取,後來發現Java api 有方法使用 subList方法,但是由於不清楚原理拿來就用,做項目就掉坑裏了

List<UclassUser> subList = list.subList(0, GameRoom.CAPACITY / 2);
                subList.forEach(item -> {
                    item.setRoomId(newRoom.getId());
                    newRoom.getStuList().add(item.getUserId());
                });
                list.removeAll(subList);
                studentAlreadyList.addAll(subList);

就是這些代碼報的錯,大家可以自行去看

查看源碼

原來subList方法是new 了一個SubList對象把原來的list引用傳了進去,所以返回的SubList對象,SubList對象也只是源集合的影像,不是新的List,所以你要是操作源集合,那麼就會報異常

throw new ConcurrentModificationException()

這種類型的異常 fail-fast,在Java中叫快速失敗,有興趣的可以去查資料

public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    }

    private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;
        private final int parentOffset;
        private final int offset;
        int size;

        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            this.parent = parent;
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = ArrayList.this.modCount;
        }

總結

最後解決辦法用新的list去接受一下,就可以操作原來的集合了

 List<UclassUser> subList = new ArrayList<>(list.subList(0, GameRoom.CAPACITY / 2));
                subList.forEach(item -> {
                    item.setRoomId(newRoom.getId());
                    newRoom.getStuList().add(item.getUserId());
                });
                list.removeAll(subList);
                studentAlreadyList.addAll(subList);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章