Generation of HashCode for list of Objects for HashMap

Viewed 65

I got that when we insert an object into a Map as Key, its hash code gets generated. But if my key is list of objects, in that case, is it the sum of all the Hash Code of objects in the list ?

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);

How can I understand this?

1 Answers

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());
Related