Java集合框架设计模式面试题
迭代器模式
Q1: Java集合框架中的迭代器模式是如何实现的?
java">public class IteratorPatternDemo {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(); }}}}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 {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);}}}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 {public class CollectionAdapterExample {public 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();}}public 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;}}}public class ViewAdapterExample {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();}}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 {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());}}}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 {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);}}}}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<>());}}}
}
面试关键点
- 理解集合框架中的设计模式应用
- 掌握迭代器模式的实现
- 熟悉组合模式的使用场景
- 了解适配器模式的应用
- 理解装饰器模式的优势
- 掌握工厂模式的实现
- 注意设计模式的选择
- 关注性能和可维护性平衡