Source From Here
Question
Is there any convenient way in List/ArrayList by which we can remove all elements of a List after a particular index. Instead of manually looping through it for removing. To be more explanatory, if I have a list of 10 elements, I want to mention index 3 and then all elements after index 3 gets removed and my list would consist of only starting 4 elements now (counts from 0)
How-To
Regarding to your question, below sample code will fit your requirement:
Sublist operations are reflected in the original list, so this clears everything from index 4 inclusive to list.size() exclusive, a.k.a. everything after index 3. Range removal is specifically used as an example in the documentation:
Below interactive groovysh shows how it works:
Question
Is there any convenient way in List/ArrayList by which we can remove all elements of a List after a particular index. Instead of manually looping through it for removing. To be more explanatory, if I have a list of 10 elements, I want to mention index 3 and then all elements after index 3 gets removed and my list would consist of only starting 4 elements now (counts from 0)
How-To
Regarding to your question, below sample code will fit your requirement:
- list.subList(4, list.size()).clear();
Below interactive groovysh shows how it works:
沒有留言:
張貼留言