1

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 snippets

3
  • 3
    Both are strange. What are you trying to do? Commented Mar 17, 2011 at 10:11
  • It's your handView.clear(); doing that removal of items. Commented Mar 17, 2011 at 10:11
  • second one is the one i have seen from tutorial ...first one i am trying to do Commented Mar 17, 2011 at 10:16

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I believe this is expected behaviour
0

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)

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.