gpt4 book ai didi

java - HashMap 顺序在使用 Thread 时发生变化,但在没有 Thread 时保持不变

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:54:02 31 4
gpt4 key购买 nike

我知道 HashMap 不保证顺序。考虑以下代码:

import java.util.HashMap;
import java.util.Map;

public class SandBox {
protected static class Book {
String name;

public Book(String name) {
this.name = name;
}

@Override
public String toString() {
return name;
}
}

protected static class MyThread extends Thread {
@Override
public void run() {
super.run();
final int n = 10;
Book[] books = new Book[n];
for (int i=0; i<n; i++)
books[i] = new Book("b" + i);
for (Book b : books)
System.out.print(b + ", ");
System.out.println();
HashMap<Book, Object> hm = new HashMap<>();
for (Book b : books)
hm.put(b, null);
for (Map.Entry<Book, Object> entry : hm.entrySet())
System.out.print(entry.getKey() + ", ");
System.out.println();
}
}

public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join();
}
}

在每次运行中,HashMap 的顺序是不同的(正如预期的那样)。例如:

输出#1:

b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, 
b3, b4, b7, b9, b0, b8, b1, b2, b6, b5,

输出#2:

b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, 
b9, b4, b3, b7, b8, b0, b1, b5, b6, b2,

但奇怪的是,如果我替换这些行

t.start();
t.join();

t.run();

(不使用多线程)输出总是一样的:

b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, 
b0, b3, b7, b4, b2, b6, b9, b1, b5, b8,

不明白HashMap的顺序和Thread的关系。有人可以向我解释为什么会这样吗?

最佳答案

这是因为 HashMap 内部顺序将取决于 hashcode 实现。

您的Book 类没有实现hashCode 所以它将使用the default one

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

这意味着它将使用内存地址。

在您的情况下,碰巧对于单个线程,分配的内存地址在重新运行时是相同的,这在线程版本中并非如此。

但这只是“偶然”,即使在单线程中你也不能依赖它(其他人会运行它并得到不同的结果,甚至当你稍后运行它时你会得到不同的结果,因为对象会有不同的内存地址)

hashmap 中使用对象时,请始终覆盖 hashCode(&equals)。

关于java - HashMap 顺序在使用 Thread 时发生变化,但在没有 Thread 时保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49506722/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com