Java中从list中删除符合条件的数据
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test1 {
java中index是什么意思public static void main(String[] args) {
ArrayList<String> strs = new ArrayList<>();
strs.add("1");
strs.add("32");
strs.add("3");
strs.add("4");
strs.add("5");
strs.add("36");
// remove1(strs);
//remove2(strs);
//remove3(strs);
remove4(strs);
System.out.println("after");
printList(strs);
}
//使⽤iterator,这个是java和Android源码中经常使⽤到的⼀种⽅法,所以最为推荐
public static void remove1(List<String> list) {
Iterator<String> sListIterator = list.iterator();
while (sListIterator.hasNext()) {
String str = ();
if (str.equals("3")) {
}
}
}
//倒序删除,以防因为删除中间项导致数据下标变更,使得数据出错
public static void remove2(List<String> list) {
for (int i = list.size() - 1; i >= 0; i--) {
if ((i).equals("3")) {
}
}
}
// 在遍历过程中不直接操作原list
public static void remove4(List<String> list) {
List<String> temp = new ArrayList<>();
for (String str : list) {
if (str.equals("3")) {
temp.add(str);
}
}
}
public static void printList(List<String> list) {
for (String str : list) {
System.out.println(str);
}
}
}
ArrayList删除源码
/
/ 移除指定索引的元素
public E remove(int index) {
// 检测指定的索引是否越界
rangeCheck(index);
modCount++;
// 获取待移除的元素,操作完成后返回
E oldValue = elementData(index);
// 计算出 index 之后元素的个数
int numMoved = size - index - 1;
if (numMoved > 0)
/
/ 调⽤ arraycopy ⽅法将 index 之后的元素向前移动⼀位,将 index 位置的元素覆盖掉
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// 将数组最后位置的值置为 null
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
根据源码可知,在删除index位置的元素时,要先调⽤rangeCheck(index)进⾏index的check,index要超过当前个数,则判定越界,抛出异常,throw new IndexOutOfBoundsException(outOfBoundsMsg(index));其他⽅法也有⽤到如:get(int index),set(int index, E element)等后⾯删除重点在于计算删除的index是末尾还是中间位置,末尾直接–,然后置空完事,如果是中间位置,那就要进⾏⼀个数组间的copy,重新组合数组数据了,性能就在这⾥得到了消耗。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。