| |
| Integer integer = new Integer(10); |
| |
| int i = integer.intValue(); |
| |
| Integer integer = 10; |
| |
| int i = integer; |
| public static Integer valueOf(int i) { |
| if (i >= IntegerCache.low && i <= IntegerCache.high) |
| return IntegerCache.cache[i + (-IntegerCache.low)]; |
| return new Integer(i); |
| } |
| private static class IntegerCache { |
| |
| static final int low = -128; |
| |
| |
| static final int high; |
| static final Integer cache[]; |
| |
| static { |
| |
| int h = 127; |
| |
| |
| |
| int i = parseInt(integerCacheHighPropValue); |
| |
| |
| i = Math.max(i, 127); |
| |
| |
| h = Math.min(i, Integer.MAX_VALUE - (-low) - 1); |
| high = h; |
| |
| |
| cache = new Integer[(high - low) + 1]; |
| |
| |
| int j = low; |
| for(int k = 0; k < cache.length; k++) |
| cache[k] = new Integer(j++); |
| |
| |
| assert IntegerCache.high >= 127; |
| } |
| } |
| |
| int a = 100; |
| Integer b = 100; |
| |
| |
| System.out.println(a == b); |
| |
| |
| Integer c = 100; |
| Integer d = 100; |
| |
| System.out.println(c == d); |
| |
| |
| c = 200; |
| d = 200; |
| |
| System.out.println(c == d); |
- 当需要进行自动装箱时,如果数字在 -128 至 127 之间时,会直接使用缓存中的对象,而不是重新创建一个对象
- 反例
| long t1 = System.currentTimeMillis(); |
| Long sum = 0L; |
| |
| for (int i = 0; i < Integer.MAX_VALUE;i++) { |
| |
| |
| sum += i; |
| } |
| long t2 = System.currentTimeMillis(); |
| System.out.println(t2-t1); |
| |
本文作者:n1ce2cv
本文链接:https://www.cnblogs.com/sprinining/p/18301486
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步