Java集合性能优化面试题
初始化优化
Q1: 如何优化集合的初始化?
java">public class CollectionInitializationExample {
public void initializationOptimization() {
List<String> badList = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
badList.add("item" + i);
}
List<String> goodList = new ArrayList<>(10000);
for (int i = 0; i < 10000; i++) {
goodList.add("item" + i);
}
int expectedSize = 10000;
float loadFactor = 0.75f;
int capacity = (int) (expectedSize / loadFactor) + 1;
Map<String, String> map = new HashMap<>(capacity);
}
public void batchInitialization() {
List<String> list1 = Arrays.asList("A", "B", "C");
List<String> list2 = List.of("A", "B", "C");
Set<String> set = Set.of("A", "B", "C");
Map<String, Integer> map = Map.of("A", 1, "B", 2, "C", 3);
}
}
Q2: 如何避免频繁的扩容和收缩?
java">public class CollectionResizingExample {
public void arrayListResizing() {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
list.add(i);
}
int expectedSize = 100000;
List<Integer> optimizedList = new ArrayList<>(expectedSize);
for (int i = 0; i < expectedSize; i++) {
optimizedList.add(i);
}
}
public void hashMapResizing() {
public static int calculateHashMapCapacity(int expectedSize) {
return (int) ((float) expectedSize / 0.75f + 1.0f);
}
int expectedSize = 10000;
Map<String, String> map = new HashMap<>(calculateHashMapCapacity(expectedSize));
}
public void avoidShrinking() {
List<String> list = new ArrayList<>(1000);
for (int i = 0; i < 1000; i++) {
list.add("item" + i);
}
list.clear();
for (int i = 0; i < list.size(); i++) {
list.set(i, null);
}
list.clear();
}
}
访问优化
Q3: 如何优化集合的访问性能?
java">public class CollectionAccessOptimization {
public void collectionTypeSelection() {
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
Set<String> hashSet = new HashSet<>();
Set<String> treeSet = new TreeSet<>();
}
public void iterationOptimization() {
List<String> list = new ArrayList<>();
int size = list.size();
for (int i = 0; i < list.size(); i++) {
}
for (int i = 0; i < size; i++) {
}
for (String item : list) {
}
}
public void batchOperations() {
List<String> source = new ArrayList<>();
List<String> target = new ArrayList<>();
for (String item : source) {
target.add(item);
}
target.addAll(source);
}
}
并发优化
Q4: 如何优化并发场景下的集合性能?
java">public class ConcurrentCollectionOptimization {
public void concurrentCollectionSelection() {
Map<String, String> concurrentMap = new ConcurrentHashMap<>();
List<String> copyOnWriteList = new CopyOnWriteArrayList<>();
BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<>();
Map<String, String> skipListMap = new ConcurrentSkipListMap<>();
}
public class CustomSegmentLockMap<K, V> {
private static final int SEGMENTS = 16;
private final Map<K, V>[] segments = new HashMap[SEGMENTS];
private final Object[] locks = new Object[SEGMENTS];
public CustomSegmentLockMap() {
for (int i = 0; i < SEGMENTS; i++) {
segments[i] = new HashMap<>();
locks[i] = new Object();
}
}
private int getSegment(K key) {
return Math.abs(key.hashCode() % SEGMENTS);
}
public V put(K key, V value) {
int segment = getSegment(key);
synchronized (locks[segment]) {
return segments[segment].put(key, value);
}
}
public V get(K key) {
int segment = getSegment(key);
synchronized (locks[segment]) {
return segments[segment].get(key);
}
}
}
public void batchOperationOptimization() {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > 100) {
map.put(entry.getKey(), entry.getValue() * 2);
}
}
map.forEach((key, value) -> {
map.compute(key, (k, v) -> v > 100 ? v * 2 : v);
});
}
}
内存优化
Q5: 如何优化集合的内存使用?
java">public class CollectionMemoryOptimization {
public void referenceManagement() {
List<Object> list = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
list.add(new Object());
}
list.clear();
for (int i = 0; i < list.size(); i++) {
list.set(i, null);
}
list.clear();
}
public void compactDataStructures() {
List<Integer> integers = new ArrayList<>();
int[] primitiveArray = new int[1000];
BitSet bitSet = new BitSet(1000);
bitSet.set(10);
boolean isSet = bitSet.get(10);
}
public class ObjectPool<T> {
private final Queue<T> pool;
private final Supplier<T> factory;
public ObjectPool(Supplier<T> factory, int initialSize) {
this.factory = factory;
this.pool = new ConcurrentLinkedQueue<>();
for (int i = 0; i < initialSize; i++) {
pool.offer(factory.get());
}
}
public T borrow() {
T obj = pool.poll();
return obj != null ? obj : factory.get();
}
public void release(T obj) {
pool.offer(obj);
}
}
}
Q6: 如何处理大规模集合数据?
java">public class LargeCollectionHandling {
public void batchProcessing() {
List<String> largeList = new ArrayList<>();
int batchSize = 1000;
for (int i = 0; i < largeList.size(); i += batchSize) {
List<String> batch = largeList.subList(
i, Math.min(i + batchSize, largeList.size())
);
processBatch(batch);
}
}
public void streamProcessing() {
List<String> largeList = new ArrayList<>();
largeList.parallelStream()
.filter(item -> item.length() > 5)
.map(String::toUpperCase)
.forEach(this::process);
}
public class ExternalStorageList<E> {
private File storageFile;
private int size;
public void add(E element) {
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(storageFile, true))) {
oos.writeObject(element);
size++;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public E get(int index) {
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(storageFile))) {
for (int i = 0; i < index; i++) {
ois.readObject();
}
return (E) ois.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
面试关键点
- 理解集合初始化的优化方法
- 掌握扩容机制的性能影响
- 了解不同访问方式的性能特点
- 熟悉并发集合的优化策略
- 掌握内存使用的优化方法
- 理解大规模数据处理方案
- 注意性能和内存的平衡
- 考虑实际应用场景的需求