ArrayList.subList

我们从一个大的ArrayList集合中截取一段数据时,经常用调用ArrayList集合的subList方法。例如

    public static void main(String[] args) {

        List<Integer> lists = new ArrayList<Integer>();
        for(int i=0; i<10; i++){
            lists.add(Integer.valueOf(i));
        }
        List<Integer> subList = lists.subList(2, 6);
        System.out.println(subList);//输出 [2, 3, 4, 5]
    }

但要注意一点,通过subList(,)方法获取的subList并不是ArrayList类型,所以不能把subList强转为ArrayList。subList其实是SubList类型,是ArrayList的子类。
通过源码可以看出

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

但注意一点,对subList对象中的数据进行修改,会影响lists中的数据

    public static void main(String[] args) {

        List<Integer> lists = new ArrayList<Integer>();
        for(int i=0; i<10; i++){
            lists.add(Integer.valueOf(i));
        }
        List<Integer> subList = lists.subList(2, 6);
        subList.clear();
        System.out.println(lists);
    }

运行程序,输出结果:

[0, 1, 6, 7, 8, 9]

可见,删除了subList对象中的数据,相应的也删除了lists中的数据。

猜你喜欢

转载自blog.csdn.net/u010502101/article/details/81138296
今日推荐