ArrayList和SubList面试题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

ArrayList和SubList面试题

芝士味的椒盐   2022-06-02 我要评论

代码复现

不要,思考一下会打印出什么?

        List<String> list1 = new ArrayList<>(Arrays.asList("username", "passwd"));
        List<String> list2 = list1.subList(0, 2);
        list2.add("email");
        System.out.println(list1);
        System.out.println(list2);

执行结果:

你是否感觉疑惑?在想为什么在list2添加的在list1也添加是吧?

源码解析

subList接口

List<E> subList(int fromIndex, int toIndex);

我们使用的是ArrayList,所以是选择ArrayList即可

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

fromIndex是从List元素开始索引,toIndex是List元素结束索引,subListRangeCheck方法是检查是否在允许范围之内。

    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
    	//开始索引小于0
        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 + ")");

重头戏在new SubList(this, 0, fromIndex, toIndex);这里,看看下面的SubList就会知道,this关键字将当前对象的引用也就是list1传入了SubList,把传入的list1变成parent赋值给SubList内部成员,然后又将这个构造生成的赋值给list2,也就是说list1和list2是引用了同一个对象,指向的是同一list。

        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;
        }

再来看看list2.add的源码,将元素直接添加在list1和list2共同的list引用对象上,这就是为什么list2添加了,list1也添加了。

        public void add(int index, E e) {
            rangeCheckForAdd(index);
            checkForComodification();
            //将元素直接添加在list1和list2共同的list引用对象上
            parent.add(parentOffset + index, e);
            this.modCount = parent.modCount;
            this.size++;
        }

附:ArrayList的subList简单介绍和使用

subList(int fromIndex, int toIndex);

它返回原来list的从[fromIndex, toIndex)之间这一部分其实就是list的子列表(注意:fromIndex是 [ 说明包括其本身,toIndex是 )说明不包括其本身)。

这个子列表的本质其实还是原列表的一部分;也就是说,修改这个子列表,将导致原列表也发生改变。

举例说明

list中包含1,2,3,4,5,6一共6个元素,list.subList(1,3)返回的是2,3(list以0为开始)

还有一个经常使用的list.subList(1,list.size)

list中包含1,2,3,4,5,6一共6个元素,list.subList(1,list.size)返回的是2,3,4,5,6(list以0为开始)

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们