Java集合框架设计模式面试题

Java集合框架设计模式面试题

迭代器模式

Q1: 集合框架中的迭代器模式是如何实现的?

java 复制代码
public class IteratorPatternExample {
    // 1. 基本迭代器使用
    public void basicIteratorUsage() {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }
    }
    
    // 2. 自定义迭代器实现
    public static class CustomCollection<T> implements Iterable<T> {
        private List<T> items = new ArrayList<>();
        
        public void add(T item) {
            items.add(item);
        }
        
        @Override
        public Iterator<T> iterator() {
            return new CustomIterator<>(items);
        }
        
        private static class CustomIterator<T> implements Iterator<T> {
            private List<T> items;
            private int position = 0;
            
            public CustomIterator(List<T> items) {
                this.items = items;
            }
            
            @Override
            public boolean hasNext() {
                return position < items.size();
            }
            
            @Override
            public T next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return items.get(position++);
            }
            
            @Override
            public void remove() {
                if (position <= 0) {
                    throw new IllegalStateException();
                }
                items.remove(--position);
            }
        }
    }
}

组合模式

Q2: 集合框架如何使用组合模式?

java 复制代码
public class CompositePatternExample {
    // 1. 组合模式示例
    public interface Component {
        void operation();
    }
    
    public class Leaf implements Component {
        private String name;
        
        public Leaf(String name) {
            this.name = name;
        }
        
        @Override
        public void operation() {
            System.out.println("Leaf " + name + " operation");
        }
    }
    
    public class Composite implements Component {
        private List<Component> children = new ArrayList<>();
        
        public void add(Component component) {
            children.add(component);
        }
        
        public void remove(Component component) {
            children.remove(component);
        }
        
        @Override
        public void operation() {
            for (Component component : children) {
                component.operation();
            }
        }
    }
    
    // 2. 实际应用示例
    public void demonstrateComposite() {
        Composite root = new Composite();
        Composite branch1 = new Composite();
        Composite branch2 = new Composite();
        
        root.add(branch1);
        root.add(branch2);
        
        branch1.add(new Leaf("A"));
        branch1.add(new Leaf("B"));
        branch2.add(new Leaf("C"));
        
        root.operation();
    }
}

适配器模式

Q3: 集合框架中的适配器模式体现在哪里?

java 复制代码
public class AdapterPatternExample {
    // 1. Arrays.asList适配器
    public void arrayListAdapter() {
        String[] array = {"A", "B", "C"};
        List<String> list = Arrays.asList(array);
        
        // 注意:这是一个固定大小的List
        try {
            list.add("D"); // 抛出UnsupportedOperationException
        } catch (UnsupportedOperationException e) {
            System.out.println("不支持修改操作");
        }
    }
    
    // 2. 自定义适配器示例
    public class SetToListAdapter<E> extends AbstractList<E> {
        private Set<E> set;
        
        public SetToListAdapter(Set<E> set) {
            this.set = set;
        }
        
        @Override
        public E get(int index) {
            if (index >= set.size()) {
                throw new IndexOutOfBoundsException();
            }
            Iterator<E> iterator = set.iterator();
            for (int i = 0; i < index; i++) {
                iterator.next();
            }
            return iterator.next();
        }
        
        @Override
        public int size() {
            return set.size();
        }
    }
}

装饰器模式

Q4: 集合框架如何使用装饰器模式?

java 复制代码
public class DecoratorPatternExample {
    // 1. Collections.unmodifiableList装饰器
    public void unmodifiableDecorator() {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        
        List<String> unmodifiableList = 
            Collections.unmodifiableList(list);
        
        try {
            unmodifiableList.add("C"); // 抛出异常
        } catch (UnsupportedOperationException e) {
            System.out.println("不能修改不可变列表");
        }
    }
    
    // 2. 自定义装饰器示例
    public class LoggingList<E> extends AbstractList<E> {
        private List<E> list;
        
        public LoggingList(List<E> list) {
            this.list = list;
        }
        
        @Override
        public E get(int index) {
            System.out.println("Getting element at index: " + index);
            return list.get(index);
        }
        
        @Override
        public void add(int index, E element) {
            System.out.println("Adding element at index: " + index);
            list.add(index, element);
        }
        
        @Override
        public E remove(int index) {
            System.out.println("Removing element at index: " + index);
            return list.remove(index);
        }
        
        @Override
        public int size() {
            return list.size();
        }
    }
}

工厂模式

Q5: 集合框架中的工厂模式是如何体现的?

java 复制代码
public class FactoryPatternExample {
    // 1. 集合工厂方法
    public static class CollectionFactory {
        public static <T> List<T> createList(boolean synchronized_) {
            return synchronized_ ? 
                Collections.synchronizedList(new ArrayList<>()) :
                new ArrayList<>();
        }
        
        public static <T> Set<T> createSet(boolean sorted) {
            return sorted ? new TreeSet<>() : new HashSet<>();
        }
        
        public static <K, V> Map<K, V> createMap(
            boolean synchronized_, boolean sorted) {
            if (synchronized_) {
                return sorted ? 
                    Collections.synchronizedMap(new TreeMap<>()) :
                    Collections.synchronizedMap(new HashMap<>());
            } else {
                return sorted ? new TreeMap<>() : new HashMap<>();
            }
        }
    }
    
    // 2. 使用示例
    public void demonstrateFactory() {
        List<String> syncList = 
            CollectionFactory.createList(true);
        Set<Integer> sortedSet = 
            CollectionFactory.createSet(true);
        Map<String, Integer> syncSortedMap = 
            CollectionFactory.createMap(true, true);
    }
}

Q6: 如何在实际项目中应用这些设计模式?

java 复制代码
public class DesignPatternApplicationExample {
    // 1. 组合迭代器模式
    public class CompositeIterator<E> implements Iterator<E> {
        private Stack<Iterator<E>> stack = new Stack<>();
        
        public CompositeIterator(Iterator<E> iterator) {
            stack.push(iterator);
        }
        
        @Override
        public boolean hasNext() {
            if (stack.empty()) {
                return false;
            }
            
            Iterator<E> iterator = stack.peek();
            if (!iterator.hasNext()) {
                stack.pop();
                return hasNext();
            }
            return true;
        }
        
        @Override
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            Iterator<E> iterator = stack.peek();
            E item = iterator.next();
            
            if (item instanceof Iterable) {
                stack.push(((Iterable<E>) item).iterator());
            }
            
            return item;
        }
    }
    
    // 2. 装饰器和适配器组合
    public class ThreadSafeListAdapter<E> 
        extends AbstractList<E> {
        private final List<E> list;
        private final Object lock = new Object();
        
        public ThreadSafeListAdapter(List<E> list) {
            this.list = list;
        }
        
        @Override
        public E get(int index) {
            synchronized (lock) {
                return list.get(index);
            }
        }
        
        @Override
        public void add(int index, E element) {
            synchronized (lock) {
                list.add(index, element);
            }
        }
        
        @Override
        public E remove(int index) {
            synchronized (lock) {
                return list.remove(index);
            }
        }
        
        @Override
        public int size() {
            synchronized (lock) {
                return list.size();
            }
        }
    }
}

面试关键点

  1. 理解集合框架中的设计模式应用
  2. 掌握迭代器模式的实现
  3. 了解组合模式的使用场景
  4. 熟悉适配器模式的应用
  5. 掌握装饰器模式的实现
  6. 理解工厂模式的作用
  7. 能够组合使用多种设计模式
  8. 注意设计模式的性能影响
相关推荐
老白干9 分钟前
jjwt 0.9.1 在 JDK 11+ 上的两个“坑”与完整解决方案
java·python·log4j
圆山猫7 小时前
[Virtualization](四):Linux KVM/RISC-V 的 vCPU 运行路径
java·linux·risc-v
城管不管7 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
IT小白杨7 小时前
从环境制备到自动化工作流:多账号运营的工程化架构拆解
java·经验分享·自动化·安全架构·指纹浏览器
豆瓣鸡8 小时前
算法日记 - Day3
java·开发语言·算法
萧瑟余晖8 小时前
Java深入解析篇九之NIO详解
java·网络·nio
The Chosen One9858 小时前
高进度算法模板速记(待完善)
java·前端·算法
笨鸟先飞,勤能补拙9 小时前
AI 赋能网络安全领域深度剖析
网络·人工智能·windows·安全·web安全·网络安全·github
我上去就是一套QWER然后等待复活10 小时前
Windows 清理 CC Switch 并恢复官方 Codex CLI 登录流程(完整记录)
windows
极光代码工作室10 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发