Why Objects.hash() returns different values for the same input?

前端 未结 1 916
悲&欢浪女
悲&欢浪女 2021-01-11 17:53

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         


        
相关标签:
1条回答
  • 2021-01-11 18:37

    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}))
    
    0 讨论(0)
提交回复
热议问题