映射(Map)
简介
Map 在有些编程语言中也叫做字典 (dictionary,比如 Python、Objective-C、Swift 等)
接口设计
/**
* Map接口定义了键值对映射的基本操作。
*
* @param <K> 键的类型
* @param <V> 值的类型
*/
public interface Map<K, V> {
/**
* 返回映射中的键值对数量。
*
* @return 键值对数量
*/
int size();
/**
* 判断映射是否为空。
*
* @return 如果映射为空,返回true;否则返回false
*/
boolean isEmpty();
/**
* 清空映射,移除所有键值对。
*/
void clear();
/**
* 将指定的键值对加入映射。
*
* @param key 要加入映射的键
* @param value 要加入映射的值
* @return 如果映射中已经存在键相同的键值对,则返回旧值;否则返回null
*/
V put(K key, V value);
/**
* 根据键获取对应的值。
*
* @param key 要获取值的键
* @return 键对应的值,如果键不存在则返回null
*/
V get(K key);
/**
* 根据键移除映射中的键值对。
*
* @param key 要移除的键
* @return 被移除的键值对的值,如果键不存在则返回null
*/
V remove(K key);
/**
* 判断映射中是否包含指定的键。
*
* @param key 要检查的键
* @return 如果映射中包含指定键,返回true;否则返回false
*/
boolean containsKey(K key);
/**
* 判断映射中是否包含指定的值。
*
* @param value 要检查的值
* @return 如果映射中包含指定值,返回true;否则返回false
*/
boolean containsValue(V value);
/**
* 遍历映射中的键值对,并根据给定的访问器进行访问。
*
* @param visitor 访问器对象
*/
void traversal(Visitor<K, V> visitor);
/**
* 访问器类定义了对映射中键值对的访问操作。
*
* @param <K> 键的类型
* @param <V> 值的类型
*/
public static abstract class Visitor<K, V> {
boolean stop;
/**
* 对映射中的键值对执行访问操作。
*
* @param key 键
* @param value 值
* @return 如果需要停止访问操作,则返回true;否则返回false
*/
public abstract boolean visit(K key, V value);
}
}
红黑树实现 TreeMap
需着重关注以下几个方法:
Node<K, V>
put
get
remove
contains
traversal
代码如下:
/**
* TreeMap 是基于红黑树实现的 Map 接口。
* 该类保证根据键的自然顺序或在创建 TreeMap 时提供的比较器的顺序进行排序。
*
* @param <K> 键的类型
* @param <V> 值的类型
*/
public class TreeMap<K, V> implements Map<K, V> {
private static final boolean RED = false; // 红色节点
private static final boolean BLACK = true; // 黑色节点
private int size; // 节点数量
private Node<K, V> root; // 根节点
private Comparator<K> comparator; // 比较器
/**
* 使用键的自然顺序构造一个空的 TreeMap。
*/
public TreeMap() {
this(null);
}
/**
* 使用给定的比较器构造一个空的 TreeMap。
*
* @param comparator 用于键排序的比较器,如果为 null 则使用键的自然顺序
*/
public TreeMap(Comparator<K> comparator) {
this.comparator = comparator;
}
/**
* 返回此映射中的键-值映射关系数。
*
* @return 映射中的键-值映射关系数
*/
@Override
public int size() {
return size;
}
/**
* 如果此映射未包含键-值映射关系,则返回 true。
*
* @return 如果此映射未包含键-值映射关系,则返回 true
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* 从此映射中移除所有映射关系。调用此方法后,映射将为空。
*/
@Override
public void clear() {
root = null;
size = 0;
}
/**
* 在此映射中关联指定值与指定键。
* 如果映射先前包含键的映射关系,则旧值被替换。
*
* @param key 与指定值关联的键
* @param value 要与指定键关联的值
* @return 与指定键关联的先前值,如果键没有映射关系,则为 null
*/
@Override
public V put(K key, V value) {
keyNotNullCheck(key);
// 添加第一个节点
if (root == null) {
root = new Node<>(key, value, null);
size++;
// 添加节点后的处理
afterPut(root);
return null;
}
// 添加的不是第一个节点
// 找到父节点
Node<K, V> parent = root;
Node<K, V> node = root;
int cmp = 0;
do {
cmp = compare(key, node.key);
parent = node;
if (cmp > 0) {
node = node.right;
} else if (cmp < 0) {
node = node.left;
} else { // 键相等
node.key = key;
V oldValue = node.value;
node.value = value;
return oldValue;
}
} while (node != null);
// 插入到父节点的位置
Node<K, V> newNode = new Node<>(key, value, parent);
if (cmp > 0) {
parent.right = newNode;
} else {
parent.left = newNode;
}
size++;
// 添加节点后的处理
afterPut(newNode);
return null;
}
/**
* 获取指定键的值。
*
* @param key 要检索其值的键
* @return 与指定键关联的值,如果映射不包含该键的映射关系,则为 null
*/
@Override
public V get(K key) {
Node<K, V> node = node(key);
return node != null ? node.value : null;
}
/**
* 从映射中移除指定键的映射关系(如果存在)。
*
* @param key 要从映射中移除其映射关系的键
* @return 与指定键关联的先前值,如果映射不包含该键的映射关系,则为 null
*/
@Override
public V remove(K key) {
return remove(node(key));
}
/**
* 如果此映射包含指定键的映射关系,则返回 true。
*
* @param key 要测试其在此映射中是否存在的键
* @return 如果此映射包含指定键的映射关系,则返回 true
*/
@Override
public boolean containsKey(K key) {
return node(key) != null;
}
/**
* 如果此映射将一个或多个键映射到指定值,则返回 true。
*
* @param value 要在此映射中查找的值
* @return 如果此映射将一个或多个键映射到指定值,则返回 true
*/
@Override
public boolean containsValue(V value) {
if (root == null) {
return false;
}
Queue<Node<K, V>> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
Node<K, V> node = queue.poll();
if (valEquals(value, node.value)) {
return true;
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return false;
}
/**
* 对映射中的每个条目执行给定操作,直到所有条目都已处理或操作引发异常。
*
* @param visitor 对每个条目执行的操作
*/
@Override
public void traversal(Visitor<K, V> visitor) {
if (visitor == null) {
return;
}
traversal(root, visitor);
}
/**
* 辅助方法,用于中序遍历树。
*
* @param node 遍历的当前节点
* @param visitor 对每个节点应用的访问者
*/
private void traversal(Node<K, V> node, Visitor<K, V> visitor) {
if (node == null || visitor.stop) {
return;
}
traversal(node.left, visitor);
if (visitor.stop) {
return;
}
visitor.visit(node.key, node.value);
traversal(node.right, visitor);
}
/**
* 检查两个值是否相等,处理 null 值。
*
* @param v1 第一个值
* @param v2 第二个值
* @return 如果值相等或都为 null,则返回 true
*/
private boolean valEquals(V v1, V v2) {
return v1 == null ? v2 == null : v1.equals(v2);
}
/**
* 从树中删除指定的节点。
*
* @param node 要删除的节点
* @return
*/
private V remove(Node<K, V> node) {
if (node == null) {
return null;
}
size--;
V oldValue = node.value;
// 如果节点有两个子节点
if (node.hasTwoChildren()) {
// 找到后继节点
Node<K, V> s = successor(node);
// 用后继节点的值覆盖度为2的节点的值
node.key = s.key;
node.value = s.value;
// 删除后继节点
node = s;
}
// 删除节点(节点的度必然是1或者0)
Node<K, V> replacement = node.left != null ? node.left : node.right;
if (replacement != null) { // 节点是度为1的节点
// 更改 parent
replacement.parent = node.parent;
// 更改 parent 的 left、right 的指向
if (node.parent == null) { // 节点是度为1的节点并且是根节点
root = replacement;
} else if (node == node.parent.left) {
node.parent.left = replacement;
} else { // node == node.parent.right
node.parent.right = replacement;
}
// 删除节点之后的处理
afterRemove(replacement);
} else if (node.parent == null) { // 节点是叶子节点并且是根节点
root = null;
} else { // 节点是叶子节点,但不是根节点
if (node == node.parent.left) {
node.parent.left = null;
} else { // node == node.parent.right
node.parent.right = null;
}
// 删除节点之后的处理
afterRemove(node);
}
return oldValue;
}
/**
* 删除节点之后的处理。
*
* @param node 被删除的节点或者用以替代被删除节点的子节点
*/
private void afterRemove(Node<K, V> node) {
// 如果删除的节点是红色,或者用以取代删除节点的子节点是红色
if (isRed(node)) {
black(node);
return;
}
Node<K, V> parent = node.parent;
if (parent == null) {
return;
}
// 删除的是黑色叶子节点【下溢】
// 判断被删除的 node 是左还是右
boolean left = parent.left == null || node.isLeftChild();
Node<K, V> sibling = left ? parent.right : parent.left;
if (left) { // 被删除的节点在左边,兄弟节点在右边
if (isRed(sibling)) { // 兄弟节点是红色
black(sibling);
red(parent);
rotateLeft(parent);
// 更换兄弟
sibling = parent.right;
}
// 兄弟节点必然是黑色
if (isBlack(sibling.left) && isBlack(sibling.right)) {
// 兄弟节点没有1个红色子节点,父节点要向下跟兄弟节点合并
boolean parentBlack = isBlack(parent);
black(parent);
red(sibling);
if (parentBlack) {
afterRemove(parent);
}
} else { // 兄弟节点至少有1个红色子节点,向兄弟节点借元素
// 兄弟节点的左边是黑色,兄弟要先旋转
if (isBlack(sibling.right)) {
rotateRight(sibling);
sibling = parent.right;
}
color(sibling, colorOf(parent));
black(sibling.right);
black(parent);
rotateLeft(parent);
}
} else { // 被删除的节点在右边,兄弟节点在左边
if (isRed(sibling)) { // 兄弟节点是红色
black(sibling);
red(parent);
rotateRight(parent);
// 更换兄弟
sibling = parent.left;
}
// 兄弟节点必然是黑色
if (isBlack(sibling.left) && isBlack(sibling.right)) {
// 兄弟节点没有1个红色子节点,父节点要向下跟兄弟节点合并
boolean parentBlack = isBlack(parent);
black(parent);
red(sibling);
if (parentBlack) {
afterRemove(parent);
}
} else { // 兄弟节点至少有1个红色子节点,向兄弟节点借元素
// 兄弟节点的左边是黑色,兄弟要先旋转
if (isBlack(sibling.left)) {
rotateLeft(sibling);
sibling = parent.left;
}
color(sibling, colorOf(parent));
black(sibling.left);
black(parent);
rotateRight(parent);
}
}
}
/**
* 返回节点的前驱节点。
*
* @param node 节点
* @return 节点的前驱节点
*/
private Node<K, V> predecessor(Node<K, V> node) {
if (node == null) {
return null;
}
// 前驱节点在左子树中(left.right.right.right....)
Node<K, V> p = node.left;
if (p != null) {
while (p.right != null) {
p = p.right;
}
return p;
}
// 从父节点、祖父节点中寻找前驱节点
while (node.parent != null && node == node.parent.left) {
node = node.parent;
}
// node.parent == null
// node == node.parent.right
return node.parent;
}
private Node<K, V> successor(Node<K, V> node) {
// 获取指定节点的后继节点
if (node == null) {
return null;
}
// 如果右子树不为空,后继节点在右子树的最左边
Node<K, V> p = node.right;
if (p != null) {
while (p.left != null) {
p = p.left;
}
return p;
}
// 从父节点、祖父节点中寻找后继节点
while (node.parent != null && node == node.parent.right) {
node = node.parent;
}
return node.parent;
}
private Node<K, V> node(K key) {
// 根据键值查找节点
Node<K, V> node = root;
while (node != null) {
int cmp = compare(key, node.key);
if (cmp == 0) {
return node;
}
if (cmp > 0) {
node = node.right;
} else { // cmp < 0
node = node.left;
}
}
return null;
}
private void afterPut(Node<K, V> node) {
// 在插入节点后修复红黑树性质
Node<K, V> parent = node.parent;
// 添加的是根节点 或者 上溢到达了根节点
if (parent == null) {
black(node);
return;
}
// 如果父节点是黑色,直接返回
if (isBlack(parent)) {
return;
}
// 叔父节点
Node<K, V> uncle = parent.sibling();
// 祖父节点
Node<K, V> grand = red(parent.parent);
if (isRed(uncle)) { // 叔父节点是红色​``【oaicite:0】``​
black(parent);
black(uncle);
// 把祖父节点当做是新添加的节点
afterPut(grand);
return;
}
// 叔父节点不是红色
if (parent.isLeftChild()) { // L
if (node.isLeftChild()) { // LL
black(parent);
} else { // LR
black(node);
rotateLeft(parent);
}
rotateRight(grand);
} else { // R
if (node.isLeftChild()) { // RL
black(node);
rotateRight(parent);
} else { // RR
black(parent);
}
rotateLeft(grand);
}
}
private void rotateLeft(Node<K, V> grand) {
Node<K, V> parent = grand.right;
Node<K, V> child = parent.left;
grand.right = child;
parent.left = grand;
afterRotate(grand, parent, child);
}
private void rotateRight(Node<K, V> grand) {
Node<K, V> parent = grand.left;
Node<K, V> child = parent.right;
grand.left = child;
parent.right = grand;
afterRotate(grand, parent, child);
}
private void afterRotate(Node<K, V> grand, Node<K, V> parent, Node<K, V> child) {
// 让parent称为子树的根节点
parent.parent = grand.parent;
if (grand.isLeftChild()) {
grand.parent.left = parent;
} else if (grand.isRightChild()) {
grand.parent.right = parent;
} else { // grand是root节点
root = parent;
}
// 更新child的parent
if (child != null) {
child.parent = grand;
}
// 更新grand的parent
grand.parent = parent;
}
private Node<K, V> color(Node<K, V> node, boolean color) {
if (node == null) {
return node;
}
node.color = color;
return node;
}
private Node<K, V> red(Node<K, V> node) {
return color(node, RED);
}
private Node<K, V> black(Node<K, V> node) {
return color(node, BLACK);
}
private boolean colorOf(Node<K, V> node) {
return node == null ? BLACK : node.color;
}
private boolean isBlack(Node<K, V> node) {
return colorOf(node) == BLACK;
}
private boolean isRed(Node<K, V> node) {
return colorOf(node) == RED;
}
private int compare(K e1, K e2) {
if (comparator != null) {
return comparator.compare(e1, e2);
}
return ((Comparable<K>) e1).compareTo(e2);
}
private void keyNotNullCheck(K key) {
if (key == null) {
throw new IllegalArgumentException("key must not be null");
}
}
private static class Node<K, V> {
K key;
V value;
boolean color = RED;
Node<K, V> left;
Node<K, V> right;
Node<K, V> parent;
public Node(K key, V value, Node<K, V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
public boolean isLeaf() {
return left == null && right == null;
}
public boolean hasTwoChildren() {
return left != null && right != null;
}
public boolean isLeftChild() {
return parent != null && this == parent.left;
}
public boolean isRightChild() {
return parent != null && this == parent.right;
}
public Node<K, V> sibling() {
if (isLeftChild()) {
return parent.right;
}
if (isRightChild()) {
return parent.left;
}
return null;
}
}
}
性能测试
测试代码
public class Main {
static void test() {
FileInfo fileInfo = Files.read("C:\\Program Files\\Java\\jdk1.8.0_321\\src\\java\\util",
new String[]{"java"});
System.out.println("文件数量:" + fileInfo.getFiles());
System.out.println("代码行数:" + fileInfo.getLines());
String[] words = fileInfo.words();
System.out.println("单词数量:" + words.length);
Map<String, Integer> map = new TreeMap<>();
for (int i = 0; i < words.length; i++) {
Integer count = map.get(words[i]);
count = (count == null) ? 1 : (count + 1);
map.put(words[i], count);
}
RuntimeCalculator.test("TreeMap", () -> map.traversal(new Visitor<String, Integer>() {
@Override
public boolean visit(String key, Integer value) {
// System.out.println(key + "_" + value);
return false;
}
}));
}
public static void main(String[] args) {
test();
}
}
测试结果
1、仅测试遍历时间
文件数量:364
代码行数:211995
单词数量:877191
【TreeMap】
开始:17:01:03.699
结束:17:01:03.701
耗时:0.001秒
-------------------------------------
进程已结束,退出代码0
2、测试存储加遍历
修改测试代码
static void test2() {
FileInfo fileInfo = Files.read("C:\\Program Files\\Java\\jdk1.8.0_321\\src\\java\\util",
new String[]{"java"});
System.out.println("文件数量:" + fileInfo.getFiles());
System.out.println("代码行数:" + fileInfo.getLines());
String[] words = fileInfo.words();
System.out.println("单词数量:" + words.length);
// 性能测试
RuntimeCalculator.test("TreeMap", new RuntimeCalculator.Task() {
@Override
public void execute() {
Map<String, Integer> map = new TreeMap<>();
for (int i = 0; i < words.length; i++) {
Integer count = map.get(words[i]);
count = (count == null) ? 1 : (count + 1);
map.put(words[i], count);
}
map.traversal(new Visitor<String, Integer>() {
@Override
public boolean visit(String key, Integer value) {
// System.out.println(key + "_" + value);
return false;
}
});
}
});
}
测试结果
文件数量:364
代码行数:211995
单词数量:877191
【TreeMap】
开始:17:10:21.305
结束:17:10:21.554
耗时:0.248秒
-------------------------------------
Map 与 Set
- Map 的所有 key 组合在一起,其实就是一个 Set(唯一不重复)
- 因此,Set 可以间接利用 Map 来作内部实现
- 源码 TreeSet 底层也是由 TreeMap 实现。
基于 TreeMap 实现 TreeSet
public class TreeSet<E> implements Set<E> {
Map<E, Object> map = new TreeMap<>();
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public void clear() {
map.clear();
}
@Override
public boolean contains(E element) {
return map.containsKey(element);
}
@Override
public void add(E element) {
map.put(element, null);
}
@Override
public void remove(E element) {
map.remove(element);
}
@Override
public void traversal(Visitor<E> visitor) {
map.traversal(new Map.Visitor<E, Object>() {
@Override
public boolean visit(E key, Object value) {
return visitor.visit(key);
}
});
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/189748.html