哈希表(Hash table),也被称为散列表,是一种基于哈希函数的数据结构,它通过把关键值(Key value)映射到表中一个位置来访问记录,从而加快查找的速度。
当我们想使用哈希法来解决问题的时候,我们一般会选择如下2种数据结构:




package main
import (
"fmt"
"sync"
)
func main() {
// 创建并操作 map
user := map[string]interface{}{
"name": "Bob",
"age": 25,
"skills": []string{"Go", "Python"},
}
// 类型断言获取值
if age, ok := user["age"].(int); ok {
user["age"] = age + 1
}
// 删除字段
delete(user, "skills")
// 并发安全操作
var wg sync.WaitGroup
var mu sync.Mutex
counter := make(map[int]int)
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
mu.Lock()
counter[i] = i * 2
mu.Unlock()
}(i)
}
wg.Wait()
fmt.Println(user) // 输出: map[age:26 name:Bob]
fmt.Println(counter) // 输出类似: map[0:0 1:2 ... 9:18]
}make(map[string]int, 1000)import java.util.*;
public class Main {
public static void main(String[] args) {
// 创建并操作 Map
Map<String, Object> user = new HashMap<>();
user.put("name", "Bob");
user.put("age", 25);
user.put("skills", new String[]{"Java", "Python"});
// 类型安全访问
if (user.get("age") instanceof Integer age) {
user.put("age", age + 1);
}
// 删除元素
user.remove("skills");
// 并发安全示例
Map<Integer, Integer> counter = new ConcurrentHashMap<>();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
final int num = i;
threads.add(new Thread(() -> {
counter.put(num, num * 2);
}));
}
threads.forEach(Thread::start);
threads.forEach(t -> {
try { t.join(); } catch (InterruptedException e) {}
});
System.out.println(user); // 输出: {name=Bob, age=26}
System.out.println(counter); // 输出: {0=0, 1=2, ..., 9=18}
}
}equals() 和 hashCode() 方法HashMap 允许 null 键和 null 值,Hashtable 不允许HashMap:无序LinkedHashMap:按插入顺序TreeMap:按键的自然顺序排序HashMapConcurrentHashMap# 创建并操作字典
inventory = {
"apples": 50,
"bananas": 25,
"oranges": 30
}
# 更新库存
def add_stock(item, quantity):
inventory[item] = inventory.get(item, 0) + quantity
add_stock("apples", 20)
add_stock("pears", 40)
# 生成报告
print("Current Inventory:")
for item, qty in inventory.items():
print(f"- {item.capitalize():<8}: {qty:03d} units")
# 删除低库存项
low_stock = [item for item, qty in inventory.items() if qty < 30]
for item in low_stock:
del inventory[item]
print("\nFinal Inventory:", inventory)输出结果:
Current Inventory:
- Apples : 070 units
- Bananas : 025 units
- Oranges : 030 units
- Pears : 040 units
Final Inventory: {'apples': 70, 'oranges': 30, 'pears': 40}注意事项:
str/int/tuple 等)collections.OrderedDict 获取更严格的有序保证dict 替代类(应使用 dataclass 或自定义类)sys.getsizeof() 查看字典内存占用__slots__ 或第三方库(如 numpy)list)作为键None 可以作为键值特性 | Python | Go | Java |
|---|---|---|---|
初始化语法 | {k: v} 或 dict() | make(map[K]V) | new HashMap<>() |
空值处理 | get(key, default) | 返回零值 | getOrDefault |
有序性 | Python 3.7+ 保持插入顺序 | 无序 | 可选有序实现 |
并发安全 | 需手动加锁 | sync.Map | ConcurrentHashMap |
默认值处理 | setdefault/defaultdict | 需手动判断 | computeIfAbsent |
今日佳句:问渠那得清如许?为有源头活水来。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。