I know that HashMap does not guarantee the order. Consider the following code:
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();
}
}
In each run, the order of HashMap is different (as expected). For example:
Output #1:
b0, b1, b2, b3, b4, b5, b6, b7, b8, b9,
b3, b4, b7, b9, b0, b8, b1, b2, b6, b5,
Output #2:
b0, b1, b2, b3, b4, b5, b6, b7, b8, b9,
b9, b4, b3, b7, b8, b0, b1, b5, b6, b2,
But the strange thing is that if I replace the lines
t.start();
t.join();
with
t.run();
(not using multithreading) the output is always the same:
b0, b1, b2, b3, b4, b5, b6, b7, b8, b9,
b0, b3, b7, b4, b2, b6, b9, b1, b5, b8,
I don't understand the relationship between HashMap's order and Thread. Can someone please explain to me why is this happening?