satheesh
satheesh

Reputation: 1451

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 snippets

Upvotes: 1

Views: 383

Answers (5)

Mr Lou
Mr Lou

Reputation: 1817

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

Upvotes: 0

amit
amit

Reputation: 10902

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.

Upvotes: 0

Daniel Rikowski
Daniel Rikowski

Reputation: 72544

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)

Upvotes: 0

DaveJohnston
DaveJohnston

Reputation: 10161

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.

Upvotes: 8

Dan D.
Dan D.

Reputation: 74685

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

Upvotes: 1

Related Questions