数组遍历:
for 遍历
public static void main(String[] args) {
long[] array = new long[100000];
for(int i = 0; i < array.length; i++){
Random r = new Random();
long tmp = r.nextLong();
array[i] = tmp;
}
long time1 = System.currentTimeMillis();
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
long time2 = System.currentTimeMillis();
System.out.println("for循环时间:" + (time2 - time1));
}
for each 遍历
long time3 = System.currentTimeMillis();
for(long l : array){
System.out.println(l);
}
long time4 = System.currentTimeMillis();
System.out.println("for each循环时间:" + (time4 - time3));for循环时间:1399,for each循环时间:1455。多次执行2种遍历时间不相上下。效率相当。推荐使用for循环,它可以通过下标访问数组元素。
ArrayList 遍历:
for循环
public static void main(String[] args) {
List<Long> array = new ArrayList<Long>();
for(int i = 0; i < 100000; i++){
Random r = new Random();
long tmp = r.nextLong();
array.add(tmp);
}
long time1 = System.currentTimeMillis();
for(int i = 0; i < array.size(); i++){
System.out.println(array.get(i));
}
long time2 = System.currentTimeMillis(); System.out.println("for循环时间:" + (time2 - time1));
}
for each循环
long time3 = System.currentTimeMillis();
for(long l : array){
System.out.println(l);
}
long time4 = System.currentTimeMillis();System.out.println("for each循环时间:" + (time4 - time3));
for循环时间:1390,for each循环时间:1395。多次执行2种遍历时间不相上下。效率相当。
LInkedList遍历:
for循环
public static void main(String[] args) {
List<Long> array = new LinkedList<Long>();
for(int i = 0; i < 100000; i++){
Random r = new Random();
long tmp = r.nextLong();
array.add(tmp);
}
long time1 = System.currentTimeMillis();
for(int i = 0; i < array.size(); i++){
System.out.println(array.get(i));
}
long time2 = System.currentTimeMillis();
System.out.println("for循环时间:" + (time2 - time1));}
for each循环
long time3 = System.currentTimeMillis();
for(long l : array){
System.out.println(l);
}
long time4 = System.currentTimeMillis();
System.out.println("for each循环时间:" + (time4 - time3));for循环时间:20634, for each循环时间:1476。foreach节省大量时间,LinkedList遍历要求使用foreach。