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. 注意设计模式的性能影响
相关推荐
感谢地心引力5 小时前
安卓、苹果手机无线投屏到Windows
android·windows·ios·智能手机·安卓·苹果·投屏
惊讶的猫5 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
jmxwzy6 小时前
Spring全家桶
java·spring·rpc
Halo_tjn6 小时前
基于封装的专项 知识点
java·前端·python·算法
Fleshy数模6 小时前
从数据获取到突破限制:Python爬虫进阶实战全攻略
java·开发语言
像少年啦飞驰点、6 小时前
零基础入门 Spring Boot:从“Hello World”到可上线的 Web 应用全闭环指南
java·spring boot·web开发·编程入门·后端开发
苍煜7 小时前
万字详解Maven打包策略:从基础插件到多模块实战
java·maven
有来技术7 小时前
Spring Boot 4 + Vue3 企业级多租户 SaaS:从共享 Schema 架构到商业化套餐设计
java·vue.js·spring boot·后端
风清扬_jd7 小时前
libtorrent-rasterbar-2.0.11编译说明
c++·windows·p2p
东东5167 小时前
xxx医患档案管理系统
java·spring boot·vue·毕业设计·智慧城市