Java List实现类面试题

news/2025/2/25 16:02:02

Java List实现类面试题

ArrayList

Q1: ArrayList的实现原理是什么?

ArrayList是基于数组实现的List,支持动态扩容。

java">public class ArrayListPrincipleExample {
    // 模拟ArrayList的基本实现
    public class SimpleArrayList<E> {
        private static final int DEFAULT_CAPACITY = 10;
        private Object[] elementData;
        private int size;
        
        public SimpleArrayList() {
            elementData = new Object[DEFAULT_CAPACITY];
        }
        
        public boolean add(E e) {
            ensureCapacity(size + 1);
            elementData[size++] = e;
            return true;
        }
        
        private void ensureCapacity(int minCapacity) {
            if (minCapacity > elementData.length) {
                int newCapacity = Math.max(elementData.length * 3/2, minCapacity);
                elementData = Arrays.copyOf(elementData, newCapacity);
            }
        }
    }
}

Q2: ArrayList的扩容机制是怎样的?

java">public class ArrayListGrowthExample {
    public void demonstrateGrowth() {
        // 1. 默认构造函数
        ArrayList<String> list1 = new ArrayList<>();  // 初始容量为0
        
        // 2. 指定初始容量
        ArrayList<String> list2 = new ArrayList<>(20);
        
        // 3. 扩容过程
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 11; i++) {
            list.add("item" + i);
            System.out.println("Size: " + list.size() + 
                             ", Capacity: " + getCapacity(list));
        }
    }
    
    // 通过反射获取实际容量
    private static int getCapacity(ArrayList<?> list) {
        try {
            Field field = ArrayList.class.getDeclaredField("elementData");
            field.setAccessible(true);
            return ((Object[]) field.get(list)).length;
        } catch (Exception e) {
            return -1;
        }
    }
}

LinkedList

Q3: LinkedList的实现原理是什么?

LinkedList是基于双向链表实现的List。

java">public class LinkedListPrincipleExample {
    // 模拟LinkedList的基本实现
    public class SimpleLinkedList<E> {
        private static class Node<E> {
            E item;
            Node<E> prev;
            Node<E> next;
            
            Node(Node<E> prev, E element, Node<E> next) {
                this.item = element;
                this.prev = prev;
                this.next = next;
            }
        }
        
        private Node<E> first;
        private Node<E> last;
        private int size;
        
        public boolean add(E e) {
            final Node<E> l = last;
            final Node<E> newNode = new Node<>(l, e, null);
            last = newNode;
            if (l == null)
                first = newNode;
            else
                l.next = newNode;
            size++;
            return true;
        }
    }
}

Q4: ArrayList和LinkedList的性能对比?

java">public class ListPerformanceComparison {
    public void comparePerformance() {
        ArrayList<Integer> arrayList = new ArrayList<>();
        LinkedList<Integer> linkedList = new LinkedList<>();
        int n = 100000;
        
        // 1. 添加性能对比
        long start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            arrayList.add(i);
        }
        System.out.println("ArrayList添加耗时:" + (System.currentTimeMillis() - start));
        
        start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            linkedList.add(i);
        }
        System.out.println("LinkedList添加耗时:" + (System.currentTimeMillis() - start));
        
        // 2. 随机访问性能对比
        start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            arrayList.get(i);
        }
        System.out.println("ArrayList随机访问耗时:" + (System.currentTimeMillis() - start));
        
        start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            linkedList.get(i);
        }
        System.out.println("LinkedList随机访问耗时:" + (System.currentTimeMillis() - start));
        
        // 3. 插入性能对比
        start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            arrayList.add(0, i);
        }
        System.out.println("ArrayList头部插入耗时:" + (System.currentTimeMillis() - start));
        
        start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            linkedList.addFirst(i);
        }
        System.out.println("LinkedList头部插入耗时:" + (System.currentTimeMillis() - start));
    }
}

实践应用

Q5: 如何选择ArrayList和LinkedList?

java">public class ListSelectionExample {
    // 1. 随机访问场景
    public void randomAccess() {
        List<Integer> list = new ArrayList<>();  // 选择ArrayList
        for (int i = 0; i < 100000; i++) {
            list.add(i);
        }
        // 随机访问元素
        Random random = new Random();
        for (int i = 0; i < 1000; i++) {
            list.get(random.nextInt(list.size()));
        }
    }
    
    // 2. 频繁插入删除场景
    public void frequentModification() {
        List<Integer> list = new LinkedList<>();  // 选择LinkedList
        // 频繁在头部插入
        for (int i = 0; i < 10000; i++) {
            list.add(0, i);
        }
        // 频繁在中间删除
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() % 2 == 0) {
                iterator.remove();
            }
        }
    }
}

Q6: List的常见陷阱有哪些?

java">public class ListPitfallsExample {
    // 1. 类型转换问题
    public void typeCastPitfall() {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        // Integer number = list.get(0);  // 自动拆箱
        Integer number = (Integer) list.get(0);  // 显式转换
    }
    
    // 2. 并发修改问题
    public void concurrentModificationPitfall() {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        
        // 错误方式
        try {
            for (String item : list) {
                if ("1".equals(item)) {
                    list.remove(item);
                }
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("并发修改异常");
        }
        
        // 正确方式
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            if ("1".equals(item)) {
                iterator.remove();
            }
        }
    }
    
    // 3. 内存泄漏问题
    public void memoryLeakPitfall() {
        List<Object> list = new ArrayList<>();
        Object obj = new Object();
        list.add(obj);
        
        // 可能导致内存泄漏
        obj = null;  // 原对象仍然被list引用
        
        // 正确方式
        list.remove(0);  // 先从list中移除
        obj = null;      // 再置空引用
    }
}

面试关键点

  1. 理解ArrayList和LinkedList的实现原理
  2. 掌握ArrayList的扩容机制
  3. 了解LinkedList的节点结构
  4. 熟悉两种List的性能特点
  5. 掌握List的选择原则
  6. 注意List使用中的陷阱
  7. 理解内存管理和性能优化
  8. 掌握并发访问的处理方式

http://www.niftyadmin.cn/n/5865682.html

相关文章

案例|某开关站室外轮式巡检机器人解决方案

随着电网规模的扩大和复杂性的增加&#xff0c;传统的GIS开关设备巡视工作面临着巨大的挑战。人工巡视不仅劳动强度大、效率低&#xff0c;而且难以保证巡视的准确性和全面性。此外&#xff0c;GIS设备通常位于复杂的环境中&#xff0c;如高海拔、高湿度、强电磁干扰等&#xf…

在嵌入式Linux中实现高并发TCP服务器:从select到epoll的演进与实战

在嵌入式Linux中实现高并发TCP服务器&#xff1a;从select到epoll的演进与实战 1. 引言&#xff1a;嵌入式网络通信的挑战与机遇 在物联网&#xff08;IoT&#xff09;和工业4.0的推动下&#xff0c;嵌入式设备逐渐从单机控制转向网络互联。然而&#xff0c;嵌入式系统的资源限…

Matlab——图像保存导出成好看的.pdf格式文件

点击图像的右上角&#xff0c;点击第一个保存按钮键。

spring-data-mongoDB

目录 spring-data-mongoDB使用 1.导入mongoDB依赖 2.编写配置文件 3.编写实体类&#xff0c;与mongoDB中的文档相对应&#xff0c;使用Document注解 4.编写service层方法 一.实现保存方法 二.实现修改方法 三.实现删除方法 四.实现查询方法 项目使用mongoDB实现作业范…

GB 44495-2024《汽车整车信息安全技术要求》标准解读|内容架构、测试内容、应对措施

一、GB 44495-2024《汽车整车信息安全技术要求》出台背景 从中国智能网联汽车产业开始发力&#xff0c;车辆信息安全开始被重视&#xff0c;近些年国内密集出台了多部相关政策文件。 2022年03月:工信部《车联网网络安全和数据安全标准体系建设指南》 2021年09月:工信部《关于…

从0-1学习Mysql第四章: 查询基础

第四章: 查询基础 在本章中&#xff0c;我们将介绍 MySQL 查询的一些基础知识。SQL 查询是从数据库中提取数据的基本操作&#xff0c;理解和掌握这些基础内容对于开发和调试数据库应用至关重要。 1. SELECT 查询 SELECT 是 SQL 查询中最常用的语句&#xff0c;用于从数据库中…

大白话React第四章战项目阶段

大白话React第四章战项目阶段 1. 选项目 这就像你要开个小店&#xff0c;得先想好卖啥东西。根据自己的兴趣和能力&#xff0c;挑个适合的项目。比如你喜欢写文章&#xff0c;就做个博客系统&#xff1b;要是喜欢整理事情&#xff0c;那就弄个待办事项应用&#xff1b;要是对…

【知识】PyTorch中不同优化器的特点和使用

转载请注明出处&#xff1a;小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你&#xff0c;欢迎[点赞、收藏、关注]哦~ 目录 1. SGD&#xff08;随机梯度下降&#xff09; 2. Adam&#xff08;自适应矩估计&#xff09; 3. AdamW 4. Adagrad 5. Adadelta 6. Adafact…