Java集合常见问题面试题
内存泄漏问题
Q1: 集合使用中常见的内存泄漏问题有哪些?如何解决?
public class CollectionMemoryLeakExample {public class StaticCollectionLeak {private static final List<Object> leakyList = new ArrayList<>();public void addItem(Object item) {leakyList.add(item); }private static final WeakHashMap<Object, Object> safeMap = new WeakHashMap<>();public void addItemSafely(Object key, Object value) {safeMap.put(key, value); }}public class CollectionReferenceLeak {private List<Object> items = new ArrayList<>();public List<Object> getItems() {return items; }public List<Object> getItemsSafely() {return Collections.unmodifiableList(items);}public List<Object> getItemsCopy() {return new ArrayList<>(items);}}public class ListenerLeak {private List<EventListener> listeners = new ArrayList<>();private List<WeakReference<EventListener>> safeListeners = new ArrayList<>();public void addEventListener(EventListener listener) {safeListeners.add(new WeakReference<>(listener));}public void fireEvent(Event event) {safeListeners.removeIf(ref -> ref.get() == null);for (WeakReference<EventListener> ref : safeListeners) {EventListener listener = ref.get();if (listener != null) {listener.onEvent(event);}}}}
}
并发修改问题
Q2: 如何处理集合的并发修改问题?
public class ConcurrentModificationExample {public class IterationModification {public void removeBadly(List<String> list) {try {for (String item : list) {if (item.isEmpty()) {list.remove(item); }}} catch (ConcurrentModificationException e) {}}public void removeSafely(List<String> list) {Iterator<String> iterator = list.iterator();while (iterator.hasNext()) {String item = iterator.next();if (item.isEmpty()) {iterator.remove(); }}}public void removeModern(List<String> list) {list.removeIf(String::isEmpty);}}public class ConcurrentAccess {private List<String> unsafeList = new ArrayList<>();private List<String> safeList = Collections.synchronizedList(new ArrayList<>());private List<String> concurrentList = new CopyOnWriteArrayList<>();public void demonstrateSafeIteration() {synchronized (safeList) {for (String item : safeList) {}}for (String item : concurrentList) {}}}
}
性能问题
Q3: 集合使用中常见的性能问题有哪些?如何优化?
public class CollectionPerformanceIssues {public class CapacityIssues {public void badCapacityUsage() {List<String> list = new ArrayList<>();for (int i = 0; i < 10000; i++) {list.add("item" + i); }}public void goodCapacityUsage() {int expectedSize = 10000;List<String> list = new ArrayList<>(expectedSize);for (int i = 0; i < expectedSize; i++) {list.add("item" + i); }}}public class SearchPerformanceIssues {public boolean badSearch(List<String> list, String target) {return list.contains(target); }public boolean goodSearch(Set<String> set, String target) {return set.contains(target); }public class IndexedSearch {private Map<String, List<Integer>> index = new HashMap<>();private List<String> data = new ArrayList<>();public void addItem(String item) {int position = data.size();data.add(item);index.computeIfAbsent(item, k -> new ArrayList<>()).add(position);}public List<Integer> findItem(String item) {return index.getOrDefault(item, Collections.emptyList());}}}public class IterationPerformanceIssues {public void badIteration(List<String> list) {for (int i = 0; i < list.size(); i++) {String item = list.get(i); }}public void goodIteration(List<String> list) {for (String item : list) { }}public void parallelProcessing(List<String> list) {list.parallelStream().filter(item -> item != null).map(String::toUpperCase).forEach(this::process);}}
}
功能问题
Q4: 如何解决集合的常见功能问题?
public class CollectionFunctionalIssues {public class SortingIssues {public class CustomSorting {private class User {private String name;private int age;}public void demonstrateSorting() {List<User> users = new ArrayList<>();Collections.sort(users, Comparator.comparing(User::getAge));Collections.sort(users, Comparator.comparing(User::getAge).thenComparing(User::getName).reversed());}}public void demonstrateStableSort() {List<String> list = new ArrayList<>();Set<String> treeSet = new TreeSet<>(list);Collections.sort(list);}}public class DuplicationIssues {public <T> List<T> removeDuplicates(List<T> list) {return new ArrayList<>(new LinkedHashSet<>(list));}public <T> List<T> removeDuplicatesBy(List<T> list, Function<T, Object> keyExtractor) {return list.stream().collect(Collectors.collectingAndThen(Collectors.toMap(keyExtractor,Function.identity(),(existing, replacement) -> existing,LinkedHashMap::new),map -> new ArrayList<>(map.values())));}}public class DeepCopyIssues {public <T extends Serializable> List<T> deepCopy(List<T> source) {try {ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bos);oos.writeObject(source);ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());ObjectInputStream ois = new ObjectInputStream(bis);return (List<T>) ois.readObject();} catch (Exception e) {throw new RuntimeException("Deep copy failed", e);}}public class CopyConstructor {private class DataHolder {private List<String> data;public DataHolder(DataHolder other) {this.data = new ArrayList<>(other.data);}}}}
}
面试关键点
- 理解内存泄漏的常见原因和解决方案
- 掌握并发修改问题的处理方法
- 了解性能优化的关键点
- 熟悉集合功能问题的解决方案
- 注意异常处理和边界情况
- 考虑线程安全问题
- 关注代码可维护性
- 重视性能和内存平衡