看了许多源代码,看见在重写hashCode方法时,基本都是乘以31,不知道这到底是为什么?

解决方案 »

  1.   

    13 31 131 331 1313 这些数字都可以个人认为,选这些数字仅仅是因为这样的hash算法更分散、效果更好
      

  2.   

    According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):     The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically. 
      

  3.   

    应该是个人需要吧。。我在看老师写的代码的时候乘以1000
    他说只要方便 怎么乘都行, 
    乘以31也是java的“潜规则”,就像创建类时候第一个字母要大写一样。
      

  4.   

    我确实也在《Effective Java 2》上看到,如此的说法