好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java中ArrayList和SubList的坑面试题

代码复现

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

?

1

2

3

4

5

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接口

?

1

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

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

?

1

2

3

4

     public List<E> subList( int fromIndex, int toIndex) {

     subListRangeCheck(fromIndex, toIndex, size);

     return new SubList( this , 0 , fromIndex, toIndex);

}

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

?

1

2

3

4

5

6

7

8

9

10

11

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。

?

1

2

3

4

5

6

7

8

9

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也添加了。

?

1

2

3

4

5

6

7

8

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为开始)

总结

到此这篇关于Java中ArrayList和SubList的坑面试题的文章就介绍到这了,更多相关ArrayList和SubList面试题内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/qq_45860349/article/details/122850216

查看更多关于Java中ArrayList和SubList的坑面试题的详细内容...

  阅读:14次