Integer源码分析

清疚 2022-03-15 14:53 365阅读 0赞

Integer

  1. public final class Integer不可被继承

其次继承了Number,实现了Comparable

Number类包括将数转换成各种类型的方法,longValue等等

参数

  1. private final int value;

保持数值的

构造方法

  1. public Integer(int value) {
  2. this.value = value;
  3. }

内部类

笔试的时候有时会比较在-128~127里面Integer的数还有大于这个范围的数,在这里面的数是相等的,大于这个数的时候,即使大小一样,执行==的时候是不一样的

  1. private static class IntegerCache {
  2. static final int low = -128;
  3. static final int high;
  4. static final Integer cache[];
  5. static {
  6. // high value may be configured by property
  7. int h = 127;
  8. String integerCacheHighPropValue =
  9. sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
  10. if (integerCacheHighPropValue != null) {
  11. try {
  12. int i = parseInt(integerCacheHighPropValue);
  13. i = Math.max(i, 127);
  14. // Maximum array size is Integer.MAX_VALUE
  15. h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
  16. } catch( NumberFormatException nfe) {
  17. // If the property cannot be parsed into an int, ignore it.
  18. }
  19. }
  20. high = h;
  21. cache = new Integer[(high - low) + 1];
  22. int j = low;
  23. for(int k = 0; k < cache.length; k++)
  24. cache[k] = new Integer(j++);
  25. // range [-128, 127] must be interned (JLS7 5.1.7)
  26. assert IntegerCache.high >= 127;
  27. }

初始化-128~127的cache值

  1. public static Integer valueOf(int i) {
  2. if (i >= IntegerCache.low && i <= IntegerCache.high)
  3. return IntegerCache.cache[i + (-IntegerCache.low)];
  4. return new Integer(i);
  5. }

在int转换的时候,如果在-128~127之间的从cache里面获得,当然这个访问的数是一样的。如果超出这个范围这new一个,当然两个数是不一样的。

String转Integer

Integer.valueOf最好用这个,因为返回的是Integer,其他函数返回的是int

发表评论

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

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

相关阅读