Java Collections工具类面试题

Java Collections工具类面试题

基本操作

Q1: Collections工具类提供了哪些常用的集合操作方法?

java 复制代码
public class CollectionsBasicExample {
    public void demonstrateBasicOperations() {
        List<Integer> list = new ArrayList<>();
        
        // 1. 添加元素
        Collections.addAll(list, 1, 2, 3, 4, 5);
        
        // 2. 排序操作
        Collections.sort(list);                     // 自然排序
        Collections.sort(list, Collections.reverseOrder()); // 反向排序
        Collections.reverse(list);                  // 反转
        Collections.shuffle(list);                  // 随机排序
        Collections.rotate(list, 2);               // 旋转
        
        // 3. 查找和替换
        int max = Collections.max(list);           // 最大值
        int min = Collections.min(list);           // 最小值
        int frequency = Collections.frequency(list, 1); // 元素出现次数
        Collections.replaceAll(list, 1, 10);       // 替换所有指定元素
        Collections.fill(list, 0);                 // 填充
        
        // 4. 二分查找
        Collections.sort(list);  // 二分查找前需要排序
        int index = Collections.binarySearch(list, 3);
    }
}

Q2: Collections工具类如何实现集合的线程安全?

java 复制代码
public class CollectionsSynchronizationExample {
    public void demonstrateSynchronization() {
        // 1. 线程安全的List
        List<String> list = new ArrayList<>();
        List<String> syncList = Collections.synchronizedList(list);
        
        // 2. 线程安全的Set
        Set<String> set = new HashSet<>();
        Set<String> syncSet = Collections.synchronizedSet(set);
        
        // 3. 线程安全的Map
        Map<String, String> map = new HashMap<>();
        Map<String, String> syncMap = Collections.synchronizedMap(map);
        
        // 4. 正确的遍历方式
        synchronized (syncList) {
            Iterator<String> i = syncList.iterator();
            while (i.hasNext())
                System.out.println(i.next());
        }
        
        // 5. 并发修改示例
        List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());
        synchronizedList.add("one");
        synchronizedList.add("two");
        
        // 错误的方式:可能抛出ConcurrentModificationException
        try {
            for (String element : synchronizedList) {
                synchronizedList.remove(element);
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("并发修改异常");
        }
        
        // 正确的方式:使用迭代器的remove方法
        synchronized (synchronizedList) {
            Iterator<String> iterator = synchronizedList.iterator();
            while (iterator.hasNext()) {
                iterator.next();
                iterator.remove();
            }
        }
    }
}

不可变集合

Q3: Collections如何创建不可变集合?

java 复制代码
public class ImmutableCollectionsExample {
    public void demonstrateImmutableCollections() {
        // 1. 空集合
        List<String> emptyList = Collections.emptyList();
        Set<String> emptySet = Collections.emptySet();
        Map<String, String> emptyMap = Collections.emptyMap();
        
        // 2. 单元素集合
        Set<String> singleton = Collections.singleton("one");
        Map<String, String> singletonMap = 
            Collections.singletonMap("key", "value");
        
        // 3. 不可修改的集合
        List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        List<String> unmodifiableList = 
            Collections.unmodifiableList(list);
        
        Set<String> set = new HashSet<>();
        set.add("one");
        Set<String> unmodifiableSet = 
            Collections.unmodifiableSet(set);
        
        Map<String, String> map = new HashMap<>();
        map.put("key", "value");
        Map<String, String> unmodifiableMap = 
            Collections.unmodifiableMap(map);
        
        // 4. 尝试修改不可变集合
        try {
            unmodifiableList.add("three"); // 抛出UnsupportedOperationException
        } catch (UnsupportedOperationException e) {
            System.out.println("不能修改不可变集合");
        }
    }
}

特殊集合

Q4: Collections提供了哪些特殊的集合实现?

java 复制代码
public class SpecialCollectionsExample {
    public void demonstrateSpecialCollections() {
        // 1. 检查型集合
        List<String> list = new ArrayList<>();
        List<String> checkedList = 
            Collections.checkedList(list, String.class);
        
        try {
            // 以下代码在编译时不会报错,但运行时会抛出ClassCastException
            List rawList = checkedList;
            rawList.add(new Integer(1));
        } catch (ClassCastException e) {
            System.out.println("类型检查失败");
        }
        
        // 2. 类型安全的枚举Set
        Set<RoundingMode> roundingModes = 
            Collections.newSetFromMap(new EnumMap<>(RoundingMode.class));
        
        // 3. 线程安全且不可修改的集合
        Set<String> set = Collections.singleton("one");
        Map<String, String> map = 
            Collections.singletonMap("key", "value");
    }
}

集合算法

Q5: Collections中的算法实现有哪些?

java 复制代码
public class CollectionsAlgorithmsExample {
    public void demonstrateAlgorithms() {
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 3, 1, 4, 1, 5, 9, 2, 6, 5);
        
        // 1. 排序算法
        Collections.sort(list);  // 自然排序
        Collections.sort(list, (a, b) -> b - a);  // 自定义排序
        
        // 2. 查找算法
        int index = Collections.binarySearch(list, 4);
        
        // 3. 极值算法
        int min = Collections.min(list);
        int max = Collections.max(list);
        
        // 4. 随机算法
        Collections.shuffle(list);  // 随机打乱
        Collections.shuffle(list, new Random(47));  // 使用指定的随机源
        
        // 5. 子列表查找
        List<Integer> subList = Arrays.asList(4, 1, 5);
        int indexOfSubList = Collections.indexOfSubList(list, subList);
        int lastIndexOfSubList = 
            Collections.lastIndexOfSubList(list, subList);
    }
}

Q6: 如何正确使用Collections工具类?

java 复制代码
public class CollectionsUsageExample {
    // 1. 集合工厂方法
    public static <T> List<T> createSafeList() {
        return Collections.synchronizedList(new ArrayList<>());
    }
    
    // 2. 不可变集合包装
    public static <T> List<T> createImmutableList(List<T> list) {
        return Collections.unmodifiableList(new ArrayList<>(list));
    }
    
    // 3. 类型安全集合
    public static <T> List<T> createCheckedList(List<T> list, 
                                              Class<T> type) {
        return Collections.checkedList(list, type);
    }
    
    // 4. 最佳实践示例
    public void demonstrateBestPractices() {
        // 使用工厂方法创建集合
        List<String> threadSafeList = createSafeList();
        
        // 创建不可变视图
        List<String> sourceList = new ArrayList<>();
        sourceList.add("one");
        List<String> immutableList = createImmutableList(sourceList);
        
        // 使用类型安全的集合
        List<String> checkedList = createCheckedList(
            new ArrayList<>(), 
            String.class
        );
        
        // 正确的同步访问
        List<String> list = Collections.synchronizedList(
            new ArrayList<>()
        );
        synchronized (list) {
            Iterator<String> i = list.iterator();
            while (i.hasNext())
                System.out.println(i.next());
        }
    }
}

面试关键点

  1. 掌握Collections工具类的常用方法
  2. 理解线程安全包装器的使用
  3. 熟悉不可变集合的创建方式
  4. 了解特殊集合的应用场景
  5. 掌握集合算法的使用
  6. 注意线程安全问题
  7. 理解类型安全的重要性
  8. 掌握最佳实践和性能考虑
相关推荐
jk_1017 分钟前
MATLAB中fft函数用法
开发语言·matlab
唔皇万睡万万睡7 分钟前
答题卡识别阅卷系统(Matlab)
开发语言·计算机视觉·matlab
zzyh12345611 分钟前
springcloud负载均衡策略有哪些
java·spring cloud·负载均衡
AlexMercer101216 分钟前
Java 入门第一课 InteliJ IDEA 的快捷操作
android·java·开发语言·ide·笔记·intellij-idea
院人冲冲冲44 分钟前
微前端qiankun打包部署
开发语言·前端·javascript
%d%d21 小时前
找不到依赖项 <…> (Maven)
java·ide·intellij-idea
五味香1 小时前
C语言学习,希尔排序
android·c语言·开发语言·数据结构·学习·算法·排序算法
小许不内卷1 小时前
TCPDF 任意文件读取漏洞:隐藏在 PDF 生成背后的危险
网络·安全
奔跑吧邓邓子1 小时前
【Python爬虫(63)】从0到1:打造图片与视频爬虫攻略
开发语言·爬虫·python·视频·图片
无际单片机编程1 小时前
单片机延时函数怎么写规范?
java·c语言·stm32·单片机·嵌入式硬件