jdk源码三 RandomAccess接口用法

本文探讨了JDK 1.4引入的RandomAccess接口的使用方法。通过示例展示,解释了实现该接口的集合如ArrayList在使用for循环遍历时的效率优势。同时,指出未实现RandomAccess接口的集合更适合用迭代器进行遍历。值得注意的是,增强for循环实际上也是基于迭代器,因此其效率与迭代器相同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jdk 1.4提供RandomAccess接口,那么它怎么用你知道吗?

先看个例子

import java.time.Instant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class RandomAccessTest {
    
    public static void main(String[] args) {
        List<Integer> list = new ArrayList();
        List<Integer> list2 = new LinkedList();
        long s = Instant.now().toEpochMilli();
        for(int i=0;i<100000;i++){
            list.add(i);
            list2.add(i);
        }
        System.out.println("实现RandomAccess接口");
        long e = Instant.now().toEpochMilli();
        System.out.println("创建数组时间是:"+(e-s)+"毫秒");

        s = Instant.now().toEpochMilli();
        for(int i=0;i<100000;i++){
            list.get(i);
        }
        e = Instant.now().toEpochMilli();
        System.out.println("for循环遍历时间是:"+(e-s)+"毫秒");

        s = Instant.now().toEpochMilli();
        Iterator<Integer> it = list.iterator();
        while (it.hasNext()){
            it.next();
        }
        e = Instant.now().toEpochMilli();
        System.out.println("迭代器遍历时间是:"+(e-s)+"毫秒");
        System.out.println("============");
        
        System.out.println("未实现RandomAccess接口");
        s = Instant.now().toEpochMilli();
        for(int i=0;i<100000;i++){
            list2.get(i);
        }
        e = Instant.now().toEpochMilli();
        System.out.println("for循环遍历时间是:"+(e-s)+"毫秒");

        s = Instant.now().toEpochMilli();
        Iterator<Integer> it2 = list2.iterator();
        while (it.hasNext()){
            it2.next();
        }
        e = Instant.now().toEpochMilli();
        System.out.println("迭代器遍历时间是:"+(e-s)+"毫秒");
    }
    

}
运行结果


说明原因先看下源码

ArrayList实现了RandomAccess接口 

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
LinkedList未实现RandomAccess接口

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
RandomAccess接口

public interface RandomAccess {
}

结论  实现了RandomAccess接口的集合,用for循环遍历效率高,没实现RandomAccess接口用迭代器遍历效率高。

注意  增强for循环底层也是采用迭代器实现,所以增强for循环和迭代器遍历是一回事。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值