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
You should have a read at the API for List.
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.