2017年3月19日 星期日

[ Java 常見問題 ] Remove all elements from a List after a particular index

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:
  1. list.subList(4, list.size()).clear();  
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:
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:
  1. list.subList(from, to).clear();  

Below interactive groovysh shows how it works:
groovy:000> list = []; (0..10).each{list.add(it)} # Crate a list for demonstration
===> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
groovy:000> list.subList(4, list.size()).clear() # Remove all element(s) after index 4 as inclusive
===> null
groovy:000> list # The removing effect reflects on original list
===> [0, 1, 2, 3]


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...