开发者

difference with ArrayList and List

Hi Here i am trying to sublist the items from list and print them 5 for each iteration. here in the following code it is printing same items every time

for(int i=0;i<4;i++)
    {
    List<Card> l=a.subList(a.size()-5, a.size());
    System.out.println(l);

 }

But here it is printing different items as if it is removing 5 from the list each time

 for(int i=0;i<4;i++){
     int deckSize = a.size();
     List<Card> handView = a.subList(deckSize-5, deckSize);
     ArrayList<Card> hand = new ArrayList<Card>(handView);
     handView.clear();
     System.out.println(hand);
 }

what is the difference between the above two code snippe开发者_开发技巧ts


You should have a read at the API for List.

The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

So in each case the list you are creating is not a new copy of the elements from the original list, but just a view into the original list. In the second example you are calling clear on the new list, which is actually clearing those elements in the original list, hence the behaviour you are seeing.


it seems that using .clear() on the result of .subList() removes the returned items form the original list


This is the designed behaviour of subList(). See the Javadoc for List.subList().

There's even an example doing almost exactly the same thing. (Removing items from a view)


Check out the doc for subList. It returns a list backed up by original list and is useful as a view. If you modify the sublist it will modify the main list. Since you cleared elements from it the original list is also modified.


List is interface.ArrayList is the class of implemention of List interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜