Java集合框架最佳实践

1. ArrayList vs LinkedList

ArrayList

  • 基于数组实现
  • 随机访问快
  • 适合频繁查询场景
  • 中间插入删除慢

LinkedList

  • 基于双向链表实现
  • 随机访问慢
  • 适合频繁增删场景
  • 内存占用较大

// ArrayList示例
List arrayList = new ArrayList<>();
arrayList.add("item1");  // O(1)
arrayList.get(0);        // O(1)
arrayList.add(0, "item0"); // O(n)

// LinkedList示例
List linkedList = new LinkedList<>();
linkedList.add("item1");     // O(1)
linkedList.addFirst("item0"); // O(1)
linkedList.get(100);         // O(n)
                    

2. HashMap最佳实践

性能优化建议

  • 合理设置初始容量,避免频繁扩容
  • 重写hashCode和equals方法
  • 使用String、Integer等不可变类作为key
  • 考虑使用EnumMap代替HashMap(当key为枚举时)

// 设置初始容量
Map userMap = new HashMap<>(32, 0.75f);

// 自定义对象作为key
public class CustomKey {
    private final String id;
    
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        CustomKey other = (CustomKey) obj;
        return Objects.equals(id, other.id);
    }
}
                    

常见陷阱

  • key的可变性导致对象丢失
  • hashCode方法实现不当导致性能问题
  • 并发环境下的线程安全问题

3. 集合框架性能优化

容量设置

如果预知集合大小,建议在创建时指定初始容量:


// 预设容量
List list = new ArrayList<>(1000);
Map map = new HashMap<>(1000);
                        

批量操作

使用批量操作方法提升性能:


// 批量添加
list.addAll(collection);  // 优于循环add

// 批量删除
list.removeAll(collection);  // 优于循环remove
                        

4. 线程安全集合

同步包装器


List syncList = Collections.synchronizedList(new ArrayList<>());
Map syncMap = Collections.synchronizedMap(new HashMap<>());
                            

并发集合


List concurrentList = new CopyOnWriteArrayList<>();
Map concurrentMap = new ConcurrentHashMap<>();