当前位置: 首页 > article >正文

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

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

迭代器模式

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

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: 集合框架如何使用组合模式?

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: 集合框架中的适配器模式体现在哪里?

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: 集合框架如何使用装饰器模式?

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: 集合框架中的工厂模式是如何体现的?

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: 如何在实际项目中应用这些设计模式?

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. 注意设计模式的性能影响

http://www.kler.cn/a/560059.html

相关文章:

  • 注意力机制深度优化
  • 【附源码】基于opencv+pyqt5搭建的人脸识别系统
  • 2025/2/17--2/23学习笔记(week1)_C语言
  • Vi 编辑器基本使用指南
  • 自动化部署工具Jenkins和Jpom的区别及优缺点,你选择用哪个?
  • C++对象模型之C++额外成本
  • React Server Components引擎的混合渲染架构:突破传统SPA的性能边际
  • CSS 使用white-space属性换行
  • 使用DDD(领域驱动设计)重构支付系统
  • 什么是CoT(带有长链思维)的Few-shot Prompting(少样本提示)
  • 网络安全之Web后端PHP
  • hab 通信
  • 全栈面试题
  • Mac中的oss上传
  • Java使用Redisson实现布隆过滤器
  • 深度优先搜索(DFS)在 Spark 中的应用与实现
  • (论文)使ConvNeXt模型适应语音数据集上的音频分类
  • Spring事务什么时候会失效
  • 【2025信息安全软考重点考点归纳】实时更新
  • Onvif协议NVR开发方案指南