Collection集合:
Collection、List、Set、Queue 全是接口
ArrayList、LinkedList、HashSet 全是实现类
LinkedList 双实现:List + Queue
1. 顶层:Collection 接口(单列根接口)
复制代码
public interface Collection<E> extends Iterable<E> {
// 增
boolean add(E e);
// 删
boolean remove(Object o);
// 查大小
int size();
// 是否为空
boolean isEmpty();
// 是否包含
boolean contains(Object o);
// 清空
void clear();
}
2. 三个子接口 继承 Collection
List 接口
复制代码
public interface List<E> extends Collection<E> {
// 特有:根据索引增删改查
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
}
Set 接口
复制代码
public interface Set<E> extends Collection<E> {
// 完全继承Collection,无特有方法
// 规则:不可重复、无索引
}
Queue 接口(队列)
复制代码
public interface Queue<E> extends Collection<E> {
// 队列特有:入队、出队、队首
boolean offer(E e);
E poll();
E peek();
}
3. 实现类源码( ArrayList / LinkedList)
ArrayList 实现 List
复制代码
public class ArrayList<E> implements List<E> {
// 底层:Object[] 数组
transient Object[] elementData;
@Override
public boolean add(E e) {
// 数组扩容 + 尾插
}
}
LinkedList 实现 List + Queue
复制代码
// 重点:同时实现两个接口
public class LinkedList<E> implements List<E>, Queue<E> {
// 底层:双向链表节点
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
}
}
HashSet 实现 Set
复制代码
public class HashSet<E> implements Set<E> {
// 底层本质:HashMap
}
4. 终极继承关系 代码版
复制代码
// 顶层
Collection
├─ List → ArrayList、LinkedList
├─ Set → HashSet
└─ Queue → LinkedList、ArrayDeque
关键=
Collection、List、Set、Queue → 全是接口
ArrayList、LinkedList、HashSet → 全是实现类
LinkedList 多实现 :implements List, Queue
Map 不继承 Collection,单独一套
Map 顶层接口(和 Collection 平级,互不继承 )
复制代码
public interface Map<K,V> {
// 增
V put(K key, V value);
// 查
V get(Object key);
// 删
V remove(Object key);
// 判空、大小
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
// 三个集合视图(核心)
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K,V>> entrySet();
// 内部静态嵌套接口:键值对条目
interface Entry<K,V> {
K getKey();
V getValue();
}
}
常用实现类 源码结构
1. HashMap(日常最常用)
复制代码
public class HashMap<K,V> implements Map<K,V> {
// 底层:数组+链表+红黑树
transient Node<K,V>[] table;
}
2. LinkedHashMap(有序)
复制代码
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {
// 保留插入顺序
}
3. TreeMap(排序)
复制代码
public class TreeMap<K,V> implements Map<K,V> {
// 底层红黑树,key自动排序
}
全集架构 终极对照
复制代码
// 单列集合 根接口
Collection
├─ List
├─ Set
└─Queue
// 双列集合 根接口(平级!不继承Collection)
Map
├─ HashMap
├─ LinkedHashMap
└─ TreeMap
总结
Collection → 单列:单个元素
Map → 双列:key-value 键值对
Map 和 Collection 完全平级,没有任何继承关系
entrySet() 就是把每一组键值对封装成 Map.Entry