1

In Java, Objects.hash(null) return 0

but

Map<Integer, Integer> map = null;
Objects.hash(map)

will return 31

1
  • null is not an object with a .hashCode() method. (And on a programming note: what would hashing null even achieve?) Commented Apr 6, 2020 at 18:00

1 Answer 1

2

It is related to how varargs are interpretted. Under the hood, varargs parameters are implemented by creating an array.

In the Objects.hash(null) case, you are passing obviously literally passing null. There is no array. When you do Objects.hash(map), this is converted to an array of length 1, with null as the first and only element.

Because of the way that hash code is calculated, null and an array with 1 null element get different hash codes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.