示例:
list1 = [10,20,30,40,50] size = 5
根据list1 = 5的大小,我需要从list2中删除最后5个元素 list2 = [11,23,32,12,21,21]
输出= [11]
因此,如果list1的大小为n,我需要从列表2中删除最后n个元素吗? 实现这一目标的有效方法是什么?
答案 0 :(得分:2)
您可以创建while-loop
,如下所示:
List yourList = ...; // Your list
int removed = 0; // Setup the variable for removal counting
while (removed < Math.min(secondList.size(), 5)) { // While we still haven't removed 5 entries OR second list size
yourList.remove(yourList.size() - 1); // Remove the last entry of the list
removed++; // Increases 'removed' count
}
答案 1 :(得分:1)
您可以考虑使用ArrayList的subList(...)方法。
答案 2 :(得分:0)
您的代码可能如下所示。
if (list1.size() >= list2.size()) {
list2.clear();
} else {
//lets iterate from position list2.size() - list1.size()
ListIterator<Integer> iterator = list2.listIterator(
list2.size() - list1.size());
while (iterator.hasNext()) {//and remove all elements after it
iterator.next();
iterator.remove();
}
}