I ran the follow script(java), and it gave me the weird result. Does anyone can help to explain?
import java.util.Objects;
import org.apache.log4j.Logger;
p
It's because hashCode
for int[]
is not overridden. There is no reason why two instances of int[]
should have the same hashCode
, even if the entries are the same.
Try this:
System.out.println(new int[] {1, 2}.hashCode());
System.out.println(new int[] {1, 2}.hashCode());
You will almost certainly see two different integers.
A good way to use Objects.hash
with arrays is to pass Arrays.hashCode(array)
instead of the actual array. In your case you could do:
Objects.hash("getDemoCache", "1", Arrays.hashCode(new int[]{1, 2}))