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

server/2025/3/1 22:32:18/

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

迭代器模式

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

java">public class IteratorPatternDemo {// 1. 基本迭代器实现public class BasicIteratorExample {public void demonstrateIterator() {List<String> list = new ArrayList<>();Iterator<String> iterator = list.iterator();// 标准迭代方式while (iterator.hasNext()) {String element = iterator.next();// 处理元素}// 安全的删除操作iterator = list.iterator();while (iterator.hasNext()) {String element = iterator.next();if (shouldRemove(element)) {iterator.remove();  // 使用迭代器的remove方法}}}}// 2. 自定义迭代器public class CustomCollection<E> implements Iterable<E> {private Object[] elements;private int size;@Overridepublic Iterator<E> iterator() {return new CustomIterator();}private class CustomIterator implements Iterator<E> {private int cursor;private int lastRet = -1;@Overridepublic boolean hasNext() {return cursor < size;}@SuppressWarnings("unchecked")@Overridepublic E next() {if (cursor >= size) {throw new NoSuchElementException();}lastRet = cursor;return (E) elements[cursor++];}@Overridepublic void remove() {if (lastRet < 0) {throw new IllegalStateException();}CustomCollection.this.remove(lastRet);cursor = lastRet;lastRet = -1;}}}
}

组合模式

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

java">public class CompositePatternDemo {// 1. 组合集合示例public class CompositeCollectionExample {// 组合接口public interface Component<E> {void add(E element);void remove(E element);Iterator<E> iterator();}// 叶子节点public class SingleCollection<E> implements Component<E> {private List<E> elements = new ArrayList<>();@Overridepublic void add(E element) {elements.add(element);}@Overridepublic void remove(E element) {elements.remove(element);}@Overridepublic Iterator<E> iterator() {return elements.iterator();}}// 组合节点public class CompositeCollection<E> implements Component<E> {private List<Component<E>> children = new ArrayList<>();@Overridepublic void add(E element) {children.forEach(child -> child.add(element));}@Overridepublic void remove(E element) {children.forEach(child -> child.remove(element));}@Overridepublic Iterator<E> iterator() {return new CompositeIterator<>(children.iterator());}public void addCollection(Component<E> collection) {children.add(collection);}}}// 2. 组合迭代器public class CompositeIterator<E> implements Iterator<E> {private Stack<Iterator<E>> stack = new Stack<>();public CompositeIterator(Iterator<E> iterator) {stack.push(iterator);}@Overridepublic boolean hasNext() {if (stack.empty()) {return false;}Iterator<E> iterator = stack.peek();if (!iterator.hasNext()) {stack.pop();return hasNext();}return true;}@Overridepublic E next() {if (!hasNext()) {throw new NoSuchElementException();}Iterator<E> iterator = stack.peek();E element = iterator.next();if (element instanceof Iterable) {stack.push(((Iterable<E>) element).iterator());}return element;}}
}

适配器模式

Q3: Java集合框架中的适配器模式是如何使用的?

java">public class AdapterPatternDemo {// 1. 集合适配器示例public class CollectionAdapterExample {// 将Enumeration适配为Iteratorpublic class EnumerationIterator<E> implements Iterator<E> {private Enumeration<E> enumeration;public EnumerationIterator(Enumeration<E> enumeration) {this.enumeration = enumeration;}@Overridepublic boolean hasNext() {return enumeration.hasMoreElements();}@Overridepublic E next() {return enumeration.nextElement();}@Overridepublic void remove() {throw new UnsupportedOperationException();}}// 将Array适配为Listpublic class ArrayAdapter<E> extends AbstractList<E> {private E[] array;public ArrayAdapter(E[] array) {this.array = array;}@Overridepublic E get(int index) {return array[index];}@Overridepublic int size() {return array.length;}@Overridepublic E set(int index, E element) {E oldValue = array[index];array[index] = element;return oldValue;}}}// 2. 视图适配器public class ViewAdapterExample {// List视图适配器public class ListViewAdapter<E> extends AbstractList<E> {private List<E> adaptee;private Function<E, E> transformer;public ListViewAdapter(List<E> adaptee, Function<E, E> transformer) {this.adaptee = adaptee;this.transformer = transformer;}@Overridepublic E get(int index) {return transformer.apply(adaptee.get(index));}@Overridepublic int size() {return adaptee.size();}}// Map视图适配器public class MapViewAdapter<K, V> extends AbstractMap<K, V> {private Map<K, V> adaptee;private BiFunction<K, V, V> transformer;public MapViewAdapter(Map<K, V> adaptee,BiFunction<K, V, V> transformer) {this.adaptee = adaptee;this.transformer = transformer;}@Overridepublic Set<Entry<K, V>> entrySet() {return new AbstractSet<Entry<K, V>>() {@Overridepublic Iterator<Entry<K, V>> iterator() {return new Iterator<Entry<K, V>>() {private Iterator<Entry<K, V>> i = adaptee.entrySet().iterator();@Overridepublic boolean hasNext() {return i.hasNext();}@Overridepublic Entry<K, V> next() {Entry<K, V> e = i.next();return new SimpleEntry<>(e.getKey(),transformer.apply(e.getKey(), e.getValue()));}};}@Overridepublic int size() {return adaptee.size();}};}}}
}

装饰器模式

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

java">public class DecoratorPatternDemo {// 1. 集合装饰器public class CollectionDecoratorExample {// 同步装饰器public class SynchronizedCollection<E> implements Collection<E> {private final Collection<E> collection;private final Object mutex;public SynchronizedCollection(Collection<E> collection) {this.collection = collection;this.mutex = this;}@Overridepublic synchronized boolean add(E e) {synchronized (mutex) {return collection.add(e);}}@Overridepublic synchronized boolean remove(Object o) {synchronized (mutex) {return collection.remove(o);}}@Overridepublic synchronized Iterator<E> iterator() {return collection.iterator();}}// 不可修改装饰器public class UnmodifiableCollection<E> implements Collection<E> {private final Collection<E> collection;public UnmodifiableCollection(Collection<E> collection) {this.collection = collection;}@Overridepublic boolean add(E e) {throw new UnsupportedOperationException();}@Overridepublic boolean remove(Object o) {throw new UnsupportedOperationException();}@Overridepublic Iterator<E> iterator() {return new UnmodifiableIterator<>(collection.iterator());}}}// 2. 自定义装饰器public class CustomDecoratorExample {// 日志装饰器public class LoggingCollection<E> implements Collection<E> {private final Collection<E> collection;private final Logger logger;public LoggingCollection(Collection<E> collection) {this.collection = collection;this.logger = LoggerFactory.getLogger(getClass());}@Overridepublic boolean add(E e) {logger.info("Adding element: {}", e);boolean result = collection.add(e);logger.info("Add result: {}", result);return result;}@Overridepublic boolean remove(Object o) {logger.info("Removing element: {}", o);boolean result = collection.remove(o);logger.info("Remove result: {}", result);return result;}}// 验证装饰器public class ValidatingCollection<E> implements Collection<E> {private final Collection<E> collection;private final Predicate<E> validator;public ValidatingCollection(Collection<E> collection,Predicate<E> validator) {this.collection = collection;this.validator = validator;}@Overridepublic boolean add(E e) {if (!validator.test(e)) {throw new IllegalArgumentException("Invalid element: " + e);}return collection.add(e);}@Overridepublic boolean addAll(Collection<? extends E> c) {c.forEach(e -> {if (!validator.test(e)) {throw new IllegalArgumentException("Invalid element in collection: " + e);}});return collection.addAll(c);}}}
}

工厂模式

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

java">public class FactoryPatternDemo {// 1. 集合工厂public class CollectionFactoryExample {// 集合工厂方法public class CollectionFactory {public static <E> List<E> createList(CollectionType type) {switch (type) {case ARRAY_LIST:return new ArrayList<>();case LINKED_LIST:return new LinkedList<>();case VECTOR:return new Vector<>();default:throw new IllegalArgumentException("Unknown type: " + type);}}public static <E> Set<E> createSet(CollectionType type) {switch (type) {case HASH_SET:return new HashSet<>();case TREE_SET:return new TreeSet<>();case LINKED_HASH_SET:return new LinkedHashSet<>();default:throw new IllegalArgumentException("Unknown type: " + type);}}public static <K, V> Map<K, V> createMap(CollectionType type) {switch (type) {case HASH_MAP:return new HashMap<>();case TREE_MAP:return new TreeMap<>();case LINKED_HASH_MAP:return new LinkedHashMap<>();default:throw new IllegalArgumentException("Unknown type: " + type);}}}}// 2. 抽象工厂public class AbstractCollectionFactoryExample {// 集合工厂接口public interface CollectionFactory {<E> List<E> createList();<E> Set<E> createSet();<K, V> Map<K, V> createMap();}// 线程安全集合工厂public class SynchronizedCollectionFactory implements CollectionFactory {@Overridepublic <E> List<E> createList() {return Collections.synchronizedList(new ArrayList<>());}@Overridepublic <E> Set<E> createSet() {return Collections.synchronizedSet(new HashSet<>());}@Overridepublic <K, V> Map<K, V> createMap() {return Collections.synchronizedMap(new HashMap<>());}}// 不可修改集合工厂public class UnmodifiableCollectionFactory implements CollectionFactory {@Overridepublic <E> List<E> createList() {return Collections.unmodifiableList(new ArrayList<>());}@Overridepublic <E> Set<E> createSet() {return Collections.unmodifiableSet(new HashSet<>());}@Overridepublic <K, V> Map<K, V> createMap() {return Collections.unmodifiableMap(new HashMap<>());}}}
}

面试关键点

  1. 理解集合框架中的设计模式应用
  2. 掌握迭代器模式的实现
  3. 熟悉组合模式的使用场景
  4. 了解适配器模式的应用
  5. 理解装饰器模式的优势
  6. 掌握工厂模式的实现
  7. 注意设计模式的选择
  8. 关注性能和可维护性平衡

http://www.ppmy.cn/server/171648.html

相关文章

【MySQL】CAST()在MySQL中的用法以及其他常用的数据类型转换函数

1. cast() CAST() 在 MySQL 中用于将一个表达式的类型转换为另一个类型。这在处理不同类型的数据时非常有用&#xff0c;比如将字符串转换为数字&#xff0c;或者将浮点数转换为整数等。 1.1 CAST() 函数的基本语法 CAST() 函数的基本语法如下&#xff1a; CAST(expression…

vue3.2 + vxe-table4.x 实现多层级结构的 合并、 展开、收起 功能

<template><div style"padding: 20px"><vxe-table border :data"list" :height"800" :span-method"rowspanMethod"><vxe-column title"一级类目" field"category1"><template #defaul…

2.部署kafka:9092

官方文档&#xff1a;http://kafka.apache.org/documentation.html (虽然kafka中集成了zookeeper,但还是建议使用独立的zk集群) Kafka3台集群搭建环境&#xff1a; 操作系统: centos7 防火墙&#xff1a;全关 3台zookeeper集群内的机器&#xff0c;1台logstash 软件版本: …

Android 8.0 (API 26) 对广播机制做了哪些变化

大部分隐式广播无法通过静态注册接收&#xff0c;除了以下白名单广播&#xff1a; ACTION_BOOT_COMPLETED ACTION_TIMEZONE_CHANGED ACTION_LOCALE_CHANGED ACTION_MY_PACKAGE_REPLACED ACTION_PACKAGE_ADDED ACTION_PACKAGE_REMOVED 需要以动态注册方案替换&#xff1a; cl…

【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus

文章目录 一、什么是 Mybatis Plus 特性 二、Spring Boot 3.0 集成 Mybatis Plus三、Mybatis Plus 查询示例 1、普通查询2、分页查询 参考 一、什么是 Mybatis Plus MyBatis-Plus&#xff08;简称 MP&#xff09;是一个 MyBatis 的增强工具&#xff0c;在 MyBatis 的基础上只…

docker通用技术介绍

docker通用技术介绍 1.docker介绍 1.1 基本概念 docker是一个开源的容器化平台&#xff0c;用于快速构建、打包、部署和运行应用程序。它通过容器化技术将应用及其依赖环境&#xff08;如代码、库、系统工具等&#xff09;打包成一个标准化、轻量级的独立单元&#xff0c;实…

使用vscode导出Markdown的PDF无法显示数学公式的问题

我的硬件环境是M2的MacBook air&#xff0c;在vscode中使用了Markdown PDF来导出md文件对应的PDF。但不管导出html还是PDF文件&#xff0c;数学公式都是显示的源代码。 我看了许多教程&#xff0c;给的是这个方法&#xff1a;在md文件对应的html文件中加上以下代码&#xff1a…

非关系型数据库和关系型数据库的区别

非关系型数据库&#xff08;NoSQL&#xff09;和关系型数据库&#xff08;SQL&#xff09;的主要区别体现在以下几个方面&#xff1a; 数据模型&#xff1a; 关系型数据库&#xff08;SQL&#xff09;&#xff1a;数据以表格形式存储&#xff0c;数据行和列组成&#xff0c;每个…