java中List.subList方法使用注意

本文转自:http://topic.csdn.net/u/20110830/13/7ea0e09c-7317-4215-96ab-fa672ea91ff8.html?91324


For example, ArrayList<Integer> aList;

获取其子链表 List<Integer> sub = aList.subList(begin, end);

sub可以继续转换成ArrayList, ArrayList<Integer> aSub = new ArrayList<Integer>(sub);

如果你使用 ArrayList<Integer> aSubList = (ArrayList<Integer>)aList.subList(begin, end);

会产生异常,因为List转换成ArrayList 是不允许的 (父类转换成子类是不允许的,因为会有数据丢失)

 

 

说明:我写此的目的不是为了抨击jdk的不好,而是为了说明这个地方可能人为引发误解。
在使用集合中,可能常常需要取集合中的某一部分子集来进行一下操作,于是subList这个方法就映入我们的眼帘,毫不犹豫地使用。

例如以下代码:

Java code
public  static  void  main( final  String[] args) { List < Object >  lists  =  new  ArrayList < Object > (); lists.add( " 1 " ); lists.add( " 2 " ); lists.add( " 3 " ); lists.add( " 4 " ); List < Object >  tempList  = lists.subList( 2 , lists.size()); tempList.add( " 6 " ); System.out.println(tempList);  //  1 System.out.println(lists);  //  2  }
 

代码初步写好后,可能我们想达到的效果是:往集合lists的子集合tempList中添加一个元素6,而原有的集合保持不变。

即到达这样的效果:lists = [1, 2, 3, 4],tempList = [3, 4, 6]。但是我们看到实际的结果确是lists里边也添加了元素6。

这是怎么一会事呢,通过查找java原代码我们可以看到:tempList的subList实现代码在AbstractList类里边,然而无论如何,最终的结果都是返回一个AbstractList的子类:SubList(该类是一个使用默认修饰符修饰的类,其源代码位于AbstractList.java类文件里边),

SubList类的构造方法:

Java code
SubList(AbstractList < E >  list,  int  fromIndex,  int  toIndex) {  if  (fromIndex  <  0 )  throw  new IndexOutOfBoundsException( " fromIndex =  "  +  fromIndex);  if  (toIndex  >  list.size())  throw  new IndexOutOfBoundsException( " toIndex =  "  +  toIndex);  if  (fromIndex  >  toIndex)  throw  new IllegalArgumentException( " fromIndex( "  +  fromIndex  +  " ) > toIndex( "  +  toIndex  +  " ) " ); l  =  list; offset  =  fromIndex; size  =  toIndex  -  fromIndex; expectedModCount  =  l.modCount; }

 

  因此,当我们使用子集合tempList进行元素的修改操作时,会影响原有的list集合。所以在使用subList方法时,一定要想清楚,是否需要对子集合进行修改元素而不影响原有的list集合。

如果需要对子集合的元素进行修改操作而不需要影响原集合时,我们可以使用以下方法进行处理:
Java code
public  static  void  main( final  String[] args) { List < Object >  lists  =  new  ArrayList < Object > (); lists.add( " 1 " ); lists.add( " 2 " ); lists.add( " 3 " ); lists.add( " 4 " );  // 注意这里是和本文顶部的代码不同的....  List < Object >  tempList  =  new  ArrayList < Object > (lists.subList( 2 , lists.size())); tempList.add( " 6 " ); System.out.println(tempList);  //  1  System.out.println(lists);  //  2  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值