hashmap什么样的元素才会跑到链表上
时间: 2024-02-23 10:17:06 浏览: 59
jdk1.7 HashMap中的致命错误:循环链表
5星 · 资源好评率100%
在 HashMap 中,当发生哈希碰撞(即不同的键映射到相同的哈希桶)时,元素会以链表的形式存储在同一个哈希桶中。具体来说,以下情况会导 xroot;
subsets[xroot].rank++;
}
}
void kruskalMST(struct Graph* graph) {
int V = graph->V;
struct Edge result[V];
int e = 0;
int i = 0;
heapSort(graph->edge, graph->E);
struct subset* subsets =
(struct subset*)malloc(V * sizeof(struct subset));
for (int v = 0; v < V; v++) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
while (e < V - 1 && i < graph->E) {
struct Edge next_edge = graph->edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
printf("边集输出:\n");
for (i = 0; i < e; ++i)
printf("%d -- %d == %d\n", result[i].src, result[i].dest,
result[i].weight);
}
```
最后,我们可以在主函数中生成一个无向图,并调用 Kruskal 算法来求解最小生成树:
```c
int main() {
int V = 4; // 顶点数量
int E = 5; // 边的数量
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->E = E;
graph->edge = (struct Edge*)malloc(graph->E * sizeof(struct Edge));
// 随机生成边集
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = 10;
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
致元素存储在链表中:
1. 哈希码相同:不同的键经过哈希函数计算 graph->edge[1].weight = 6;
graph->edge[2].src = 0;
graph->edge[2后得到相同的哈希码。
2. equals() 方法返回 true:当两个键的哈希码相等时].dest = 3;
graph->edge[2].weight = 5;
graph->edge[3].src = 1,它们会被放置在同一个哈希桶中。然后,通过 equals() 方法比较两个键的值。如果 equals() 方法返回 true,则表示这两个键相等,它们会被存储在链表中。
3. 哈希桶中已经存在其他键值对:当哈希桶中已经存在一个或多个键值对时,;
graph->edge[3].dest = 3;
graph->edge[3].weight = 15;
graph->edge新的键值对会被添加到链表的末尾。
需要注意的是,Java 8 中引入了红黑[4].src = 2;
graph->edge[4].dest = 3;
graph->edge[4].weight =树来替代链表,当链表长度超过阈值(默认为8)时,链表会自动转换为红黑树,以提高查找效率。
阅读全文