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. 掌握最佳实践和性能考虑
相关推荐
于壮士hoho几秒前
Python | Dashboard制作
开发语言·python
2301_803554521 分钟前
c++和c的不同
java·c语言·c++
开发游戏的老王21 分钟前
[虚幻官方教程学习笔记]深入理解实时渲染(An In-Depth Look at Real-Time Rendering)
笔记·学习·虚幻
意倾城32 分钟前
JVM内存模型
java·jvm
彬彬醤42 分钟前
查询电脑伪装IP,网络安全速查攻略!
网络·网络协议·tcp/ip·安全·web安全·http·https
普通的冒险者44 分钟前
几个简单的数组小练习(适合初学)
java·数据结构
keke1044 分钟前
Java【10_1】用户注册登录(面向过程与面向对象)
java·python·intellij-idea
程序员buddha44 分钟前
Spring & Spring Boot 常用注解整理
java·spring boot·spring
Asus.Blogs1 小时前
为什么go语言中返回的指针类型,不需要用*取值(解引用),就可以直接赋值呢?
开发语言·后端·golang
青瓦梦滋1 小时前
【语法】C++的多态
开发语言·c++