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. 注意设计模式的性能影响
相关推荐
长沙火山12 分钟前
9.ArkUI List的介绍和使用
数据结构·windows·list
purrrew16 分钟前
【JAVA ee初阶】多线程(3)
java·开发语言
每次的天空24 分钟前
Android学习总结之Java篇(一)
android·java·学习
尤物程序猿1 小时前
【2025最新Java面试八股】如何在Spring启动过程中做缓存预热?
java·缓存·面试
春眠不觉晓♞1 小时前
使用多线程快速向Excel中快速插入一万条数据案例
java·学习·excel
fantasy_42 小时前
LeetCode238☞除自身以外数组的乘积
java·数据结构·python·算法·leetcode
GalenZhang8882 小时前
Java生成微信小程序码及小程序短链接
java·微信小程序·小程序
元亓亓亓2 小时前
Java后端开发day38--不可变集合&Stream流
java·开发语言
纪元A梦2 小时前
华为OD机试真题——阿里巴巴找黄金宝箱Ⅰ(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
java·c语言·javascript·c++·python·华为od·go
智想天开2 小时前
13.组合模式:思考与解读
docker·设计模式·容器·组合模式