自动装箱和自动拆箱

自动装箱 auto-boxing

基本类型就是自动地封装到与它相同的类型的包装类中

Integer i=100;

编译器调用了valueOf()方法

Integer i=Integer.valueOf(100);

 

Integer中的缓存类IntegerCache

       Cache为【-128.127】.IntegerCache有一个静态的Integer数组,在类加载时就将-128到127的Integer对象创建了,并保存在cache数组中,一旦程序调用了valueOf方法,如果取的值是在-128到127之间就直接在cache缓存中去取Integer对象,超出范围就new 一个对象。【详见jdk源码及api】

自动拆箱  unboxing

包装类对象自动转换成基本类型数据。

int a=new Integer(100);

编译器为我们添加了

int a=new Integer(100).int value();

 

 

复制代码
 1 public class TestAutoBoxing {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5     //反编译工具更详细来理解    
 6         
 7 Integer a=100;//自动装箱
 8 Integer b=100;
 9 System.out.println(a==b);
10 Integer aa=1000;
11 Integer bb=1000;
12 System.out.println(aa==bb);
13 
14 int a1=new Integer(100);
15 //相当于 new Integer(100).intvalue();
16 
17 Integer b1=null;
18 int c1=b1;//自动拆箱
19 //相当于
20 int cc=b.intValue();
21 System.out.println(c1);
22 
23 
24 
25     }
26 
27 }
复制代码

 

Integer 中的缓存类 IntegerCache


Cache 为[-128,127],IntegerCache 有一个静态的 Integer 数
组,在类加载时就将-128 到 127 的 Integer 对象创建了,并
保存在 cache 数组中,一旦程序调用 valueOf 方法,如果取
的值是在-128 到 127 之间就直接在 cache 缓存数组中去取
Integer 对象,超出范围就 new 一个对象

posted @   wq9  阅读(230)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示