Reputation: 4401
i have an ArrayList with elements for example:
[a,b,c,d,e,f,g,h];
and need to take elements [a,b,c]
also it should be an ArrayList and remove them from first List and again i take some elements from first list after i take i remove them.
So what is the best way (considering a time) to do this job ? I mean i should iterate over elements or should convert to array and than work with it ?
maybe there are some fast way to do this ?
Thanks.
Upvotes: 0
Views: 242
Reputation: 66109
Create a new list using subList()
to get a view into the first, then use clear()
on the subList. Example:
subList = originalList.subList(0, 3);
newList = new ArrayList(subList);
subList.clear();
This is much more efficient than iterating over the original list removing one element at a time since removing an element from an ArrayList involves shifting all the elements. Using a subList
does the shift just once.
Upvotes: 1
Reputation: 4507
You could use the sublist
method to split this list into two (making two calls to sublist
).
Upvotes: 0