Integer对象

  1. 内部静态类IntegerCache会缓存-128-127的值,
  2. equals比较的值
  3. hashcode返回的是值
  4. compareTo比较的值 ```java package java.lang;

import java.lang.annotation.Native;

public final class Integer extends Number implements Comparable {

  1. /**
  2. * 缓存范围 -128 and 127 (inclusive) as required by JLS.
  3. *
  4. * 可以通过参数调节 {@code -XX:AutoBoxCacheMax=<size>} option.
  5. */
  6. private static class IntegerCache {
  7. static final int low = -128;
  8. static final int high;
  9. static final Integer cache[];
  10. static {
  11. // high value may be configured by property
  12. int h = 127;
  13. //省略通过获取参数来调节h的代码,可以大于等于127 ,小于127则取127
  14. high = h;
  15. cache = new Integer[(high - low) + 1];
  16. int j = low;
  17. for(int k = 0; k < cache.length; k++)
  18. cache[k] = new Integer(j++);
  19. // range [-128, 127] must be interned (JLS7 5.1.7)
  20. assert IntegerCache.high >= 127;
  21. }
  22. private IntegerCache() {}
  23. }
  24. /**
  25. * 判断是否属于缓存范围内,如果属于则从缓存中获取Integer对象
  26. */
  27. public static Integer valueOf(int i) {
  28. if (i >= IntegerCache.low && i <= IntegerCache.high)
  29. return IntegerCache.cache[i + (-IntegerCache.low)];
  30. return new Integer(i);
  31. }
  32. /**
  33. * Integer hashcode 返回的是原值
  34. */
  35. @Override
  36. public int hashCode() {
  37. return Integer.hashCode(value);
  38. }
  39. public static int hashCode(int value) {
  40. return value;
  41. }
  42. /**
  43. *使用Integer.equals()进行比较时,比较的是值
  44. */
  45. public boolean equals(Object obj) {
  46. if (obj instanceof Integer) {
  47. return value == ((Integer)obj).intValue();
  48. }
  49. return false;
  50. }
  51. /**
  52. * 使用Integer.compareTo()进行比较时,比较的是值.
  53. */
  54. public int compareTo(Integer anotherInteger) {
  55. return compare(this.value, anotherInteger.value);
  56. }
  57. public static int compare(int x, int y) {
  58. return (x < y) ? -1 : ((x == y) ? 0 : 1);
  59. }
  60. /** use serialVersionUID from JDK 1.0.2 for interoperability */
  61. @Native private static final long serialVersionUID = 1360826667806852920L;

}

```

hashcode

如果equals()返回true,则2个对象的哈希码必须相同,如果equals()返回false,则应该(但不是必需)不同。同样通过Object.hashCode()的声明,它必须是int。理想情况下,哈希码应该依赖于散列的所有数据。 PLASHHOLDER_FOR_CODE_10的哈希码 Long必须将8个字节映射到4个字节(int的大小)。 Long.hashCode()的当前实现只会返回i(如果它适合int),否则它将与高32位(4字节)进行异或运算