- 通过迭代器遍历。即通过Iterator去遍历。
Integer value = null;
int size = vec.size();
for (int i=0; i<size; i++) {
value = (Integer)vec.get(i);
}
- 随机访问,通过索引值去遍历。
由于Vector实现了RandomAccess接口,它支持通过索引值去随机访问元素。
Integer value = null;
int size = vec.size();
for (int i=0; i<size; i++) {
value = (Integer)vec.get(i);
}
- 另一种for循环。如下:
Integer value = null;
for (Integer integ:vec) {
value = integ;
}
- Enumeration遍历。如下:
Integer value = null;
Enumeration enu = vec.elements();
while (enu.hasMoreElements()) {
value = (Integer)enu.nextElement();
}
实例:
package day_3_29;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.RandomAccess;
import java.util.Vector;
public class VectorRandomAccessTest {
public static void main(String[] args) {
Vector vec = new Vector();
for (int i = 0; i < 100000; i++)
vec.add(i);
isRandomAccessSupported(vec);
iteratorThroughRandomAccess(vec);
iteratorThroughIterator(vec);
iteratorThroughFor2(vec);
iteratorThroughEnumeration(vec);
}
private static void isRandomAccessSupported(List list) {
if (list instanceof RandomAccess) {
System.out.println("RandomAccess implemented!");
} else {
System.out.println("RandomAccess not implemented!");
}
}
public static void iteratorThroughRandomAccess(List list) {
long startTime;
long endTime;
startTime = System.currentTimeMillis();
for (int i = 0; i < list.size(); i++) {
list.get(i);
}
endTime = System.currentTimeMillis();
long interval = endTime - startTime;
System.out.println("iteratorThroughRandomAccess:" + interval + " ms");
}
public static void iteratorThroughIterator(List list) {
long startTime;
long endTime;
startTime = System.currentTimeMillis();
for (Iterator iter = list.iterator(); iter.hasNext();) {
iter.next();
}
endTime = System.currentTimeMillis();
long interval = endTime - startTime;
System.out.println("iteratorThroughIterator:" + interval + " ms");
}
public static void iteratorThroughFor2(List list) {
long startTime;
long endTime;
startTime = System.currentTimeMillis();
for (Object obj : list)
;
endTime = System.currentTimeMillis();
long interval = endTime - startTime;
System.out.println("iteratorThroughFor2:" + interval + " ms");
}
public static void iteratorThroughEnumeration(Vector vec) {
long startTime;
long endTime;
startTime = System.currentTimeMillis();
for (Enumeration enu = vec.elements(); enu.hasMoreElements();) {
enu.nextElement();
}
endTime = System.currentTimeMillis();
long interval = endTime - startTime;
System.out.println("iteratorThroughEnumeration:" + interval + " ms");
}
}