『java.util』 list 接口研究

list接口继承collection,除了有collection提供的方法外,还额外的带来了几个list方法:

1. boolean addAll(int index, collection<? extends E> c); 

在指定的位置添加,这个位置是从0开始计算的,就是说如果index为0,则这个集合在开头插入。


2. E get(int index); 

 

3.E set(int index ,E element);


4. void add(int index ,E element);


5. E remove(int index) ;Removes the element at the specified position in this list (optional operation).  Shifts any subsequent elements to the left (subtracts one  from their indices).  Returns the element that was removed from the list. 删除指定的位置的E,并将这个E返回


6. int indexOf(Object o); Returns the index of the first occurrence of the specified element  in this list, or -1 if this list does not contain the element.More formally, returns the lowest index <tt>i</tt> such that <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,or -1 if there is no such index. 返回o第一次在集合中的位置。


7.int indexOf(Object o); Returns the index of the last occurrence of the specified element  in this list, or -1 if this list does not contain the element.  More formally, returns the highest index <tt>i</tt> such that <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,  or -1 if there is no such index. 返回o最后一次出现的位置,如果这两个位置相等的话,那说明collection里面只有一个o。


8.ListIterator<e> listIterator();Returns a list iterator over the elements in this list (in proper  sequence).与iterator的区别

1、Iterator可用来遍历Set和List集合,但是ListIterator只能用来遍历List。
2、Iterator对集合只能是前向遍历,ListIterator既可以前向也可以后向。
3、ListIterator实现了Iterator接口,并包含其他的功能,比如:增加元素,替换元素,获取前一个和后一个元素的索引,等等。


9.ListIterator<e> listIterator(int index); 从指定位置开始的E到最后之间的E,返回到一个iterator中,


10.List<E> subList(int fromIndex, int toIndex); Returns a view of the portion of this list between the specified <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is empty.)  The returned list is backed by this list, so non-structural  changes in the returned list are reflected in this list, and vice-versa.  The returned list supports all of the optional list operations supported  by this list.  

注意:

它返回原来list的从[fromIndex, toIndex)之间这一部分的视图,之所以说是视图,是因为实际上,返回的list是靠原来的list支持的。

所以,你对原来的list和返回的list做的“非结构性修改”(non-structural changes),都会影响到彼此对方。

所谓的“非结构性修改”,是指不涉及到list的大小改变的修改。相反,结构性修改,指改变了list大小的修改。

 

那么,如果涉及到结构性修改会怎么样呢?

如果发生结构性修改的是返回的子list,那么原来的list的大小也会发生变化;

而如果发生结构性修改的是原来的list(不包括由于返回的子list导致的改变),那么返回的子list语义上将会是undefined。在AbstractList(ArrayList的父类)中,undefined的具体表现形式是抛出一个ConcurrentModificationException。

因此,如果你在调用了sublist返回了子list之后,如果修改了原list的大小,那么之前产生的子list将会失效,变得不可使用。

 

tips: 如何删除一个list的某个区段,比如删除list的第2-5个元素?

方法是: 可以利用sublist的幕后还是原来的list的这个特性,比如

list.subList(from, to).clear();

这样就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值