1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Lolly
  • 34,250
  • 42
  • 115
  • 150
  • This is dictated by the `List` contract. [See the Javadocs](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#hashCode--) – ernest_k Apr 07 '22 at 15:35

1 Answers1

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());
eekboom
  • 5,551
  • 1
  • 30
  • 39