为 HashMap 的对象列表生成 HashCode

Lol*_*lly 1 java hashmap

我发现当我们将一个对象作为键插入到 Map 中时,它的哈希代码就会生成。但是如果我的键是对象列表,在这种情况下,它是列表中所有对象的哈希码的总和吗?

User user1 = new User(13, "Ron", "ron@gmail.com");
User user2 = new User(15, "Kamden", "kamden@gmail.com");
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
Map<List<User>, User> userMap = new HashMap<>();
userMap.put(userList, user1);
Run Code Online (Sandbox Code Playgroud)

我该如何理解这一点?

Ste*_*ich 5

That's actually specified in the JavaDoc. The ArrayList javadocs tells you to look at the implementation in AbstractList, and AbstractList.hashCode() says the implementation is the same as in List.hashCode which gives this definition

The hash code of a list is defined to be the result of the following calculation:

int hashCode = 1;
for (E e : list)
    hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
Run Code Online (Sandbox Code Playgroud)