java连续删除list中的数据
一个list列表中有40个数据,连续删除第20到30个数据。
错误示范
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < 40; i++ ){
list.add(i);
}
for(int i = 20; i < 30; i++){
list.remove(i);
}
StringBuilder stringBuilder = new StringBuilder();
for(int element: list){
stringBuilder.append(" " + element);
}
System.out.println("element =" + stringBuilder.toString() );
}
element = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 21 23 25 27 29 31 33 35 37 39
发现删除错了。
正确做法
1、使用迭代器
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < 40; i++ ){
list.add(i);
}
Iterator<Integer> iterator = list.iterator();
int removeIndex = -1;
while (iterator.hasNext()){
if(removeIndex >= 30){
break;
}
++removeIndex;
if(removeIndex < 20){
iterator.next();
continue;
}
iterator.next();
iterator.remove();
}
StringBuilder stringBuilder = new StringBuilder();
for(int element: list){
stringBuilder.append(" " + element);
}
System.out.println("element =" + stringBuilder.toString() );
}
2、使用sublist
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < 40; i++ ){
list.add(i);
}
list.subList(20, 30).clear();
StringBuilder stringBuilder = new StringBuilder();
for(int element: list){
stringBuilder.append(" " + element);
}
System.out.println("element =" + stringBuilder.toString() );
}
|