Integer源码学习笔记

r囧r小猫 2022-05-30 00:56 265阅读 0赞
  1. 1 public final class Integer extends Number implements Comparable<Integer>
  2. 2toString( )方法先得到参数i的长度,然后以该长度生成char类型的buf数组,最后以该buf数组作为参数调用new String(buf, true)生成一个String对象。必须先判断Integer.MIN_VALUE,因为getChars()方法中使用了i=-i,以负数为基准,对于i=Integer.MIN_VALUE将会产生溢出。
  3. public static String toString(int i) {
  4. if (i == Integer.MIN_VALUE)
  5. return "-2147483648";
  6. int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
  7. char[] buf = new char[size];
  8. getChars(i, size, buf);
  9. return new String(buf, true);
  10. }
  11. 3、调用Integer.valueOf( )方法时先判断给定的数是否在-128~127之间(其中-128写死,而127值可以设置),若在该范围内,直接返回Cache数组中的Integer对象(见5),否则生成一个Integer对象。
  12. public static Integer valueOf(int i) {
  13. if (i >= IntegerCache.low && i <= IntegerCache.high)
  14. return IntegerCache.cache[i + (-IntegerCache.low)];
  15. return new Integer(i);
  16. }
  17. 4、覆盖了Object类中的hashcode函数,Integer内部定义了final类型的int变量保存该Integer的值,该Integer对象的hashcode即是其value值。
  18. private final int value;
  19. public Integer(int value) {
  20. this.value = value;
  21. }
  22. @Override
  23. public int hashCode() {
  24. return Integer.hashCode(value);
  25. }
  26. public static int hashCode(int value) {
  27. return value;
  28. }
  29. public boolean equals(Object obj) {
  30. if (obj instanceof Integer) {
  31. return value == ((Integer)obj).intValue();
  32. }
  33. return false;
  34. }
  35. 5 Integer内部定义了一个私有的静态内部类IntegerCache,内部定义了一个Integer类型的cache数组,若给定的数在lowhigh之间,直接返回该数组中的Integer对象。
  36. private static class IntegerCache {
  37. static final int low = -128;
  38. static final int high;
  39. static final Integer cache[];
  40. static {
  41. // high value may be configured by property
  42. int h = 127;
  43. String integerCacheHighPropValue =
  44. sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
  45. if (integerCacheHighPropValue != null) {
  46. try {
  47. int i = parseInt(integerCacheHighPropValue);
  48. i = Math.max(i, 127);
  49. // Maximum array size is Integer.MAX_VALUE
  50. h = Math.min(i, Integer.MAX_VALUE-(-low) -1);
  51. } catch( NumberFormatException nfe) {
  52. }
  53. }
  54. high = h;
  55. cache = new Integer[(high - low) + 1];
  56. int j = low;
  57. for(int k = 0; k < cache.length; k++)
  58. cache[k] = new Integer(j++);
  59. assert IntegerCache.high >= 127;
  60. }
  61. private IntegerCache() {}
  62. }
  63. 6@Native public static final int MIN_VALUE = 0x80000000;
  64. @Native public static final int MAX_VALUE = 0x7fffffff;
  65. Int类型的数值范围为 ,即-2147483648~2147483647,将0x80000000转换成二进制即为10000000 0000000 00000000 00000000,最高位代表符号位。单字节有符号整数可以存储的范围是-128~127,正数二进制表示范围0000 0000~0111 1111,即1~127,负数二进制表示范围1000 0001 ~1111 1111,即-1~-127,还有个0分别为+0和-0, 0000 0000表示+01000 0000表示-128,同理可得10000000 0000000 00000000 00000000表示-2147483648

发表评论

表情:
评论列表 (有 0 条评论,265人围观)

还没有评论,来说两句吧...

相关阅读