package test; import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List; public class TestList {
static final int size = 1000000; public static void main(String[] args) {
List<Integer> linkedList = new LinkedList<Integer>();
List<Integer> arrayList = new ArrayList<Integer>();
long startTime;
long endTime;
Iterator<Integer> iterator; //添加数据
for (int i = 0; i < size; i++) {
int value = (int) (Math.random() * 1000);
if (value == 0) {
linkedList.add(null);
} else {
linkedList.add(value);
}
}
arrayList.addAll(linkedList); //采用倒叙方法移除空元素
arrayList.clear();
arrayList.addAll(linkedList);
startTime = System.currentTimeMillis();
for (int i = arrayList.size() - 1; i >= 0; i--) {
if (arrayList.get(i) == null) {
arrayList.remove(i);
}
}
endTime = System.currentTimeMillis();
System.out.println("倒叙方法移除ArrayList中null 耗时" + (endTime - startTime) + "ms, 剩余数据" + arrayList.size() + "个"); arrayList.clear();
arrayList.addAll(linkedList);
int len = arrayList.size();
startTime = System.currentTimeMillis();
for (int i = 0; i < len; i++) {
if (arrayList.get(i) == null) {
arrayList.remove(i);
i--;
len--;
}
}
endTime = System.currentTimeMillis();
System.out.println("正序方法移除ArrayList中null 耗时" + (endTime - startTime) + "ms, 剩余数据" + arrayList.size() + "个"); arrayList.clear();
arrayList.addAll(linkedList);
startTime = System.currentTimeMillis();
arrayList.removeAll(Collections.singleton(null));
endTime = System.currentTimeMillis();
System.out.println("Collections方法移除ArrayList中null 耗时" + (endTime - startTime) + "ms, 剩余数据" + arrayList.size() + "个"); arrayList.clear();
arrayList.addAll(linkedList);
startTime = System.currentTimeMillis();
iterator = arrayList.iterator();
while (iterator.hasNext()) {
Integer valueInteger = iterator.next();
if (valueInteger == null) {
iterator.remove();
}
}
endTime = System.currentTimeMillis();
System.out.println("迭代器方法移除ArrayList中null 耗时" + (endTime - startTime) + "ms, 剩余数据" + arrayList.size() + "个"); startTime = System.currentTimeMillis();
iterator = linkedList.iterator();
while (iterator.hasNext()) {
Integer valueInteger = iterator.next();
if (valueInteger == null) {
iterator.remove();
}
}
endTime = System.currentTimeMillis();
System.out.println("迭代器方法移除LinkedList中null 耗时" + (endTime - startTime) + "ms, 剩余数据" + arrayList.size() + "个"); } }
结果(跟List中null元素个数有关):
倒叙方法移除ArrayList中null 耗时126ms, 剩余数据998946个
正序方法移除ArrayList中null 耗时122ms, 剩余数据998946个
Collections方法移除ArrayList中null 耗时13ms, 剩余数据998946个
迭代器方法移除ArrayList中null 耗时131ms, 剩余数据998946个
迭代器方法移除LinkedList中null 耗时12ms, 剩余数据998946个