优秀的编程知识分享平台

网站首页 > 技术文章 正文

int和Integer区别

nanyue 2025-05-27 16:41:31 技术文章 3 ℃

在 Java 中,int 和 Integer 是两种不同的数据类型,核心区别如下:

基本类型 vs. 包装类

特性

int

Integer

类型

基本数据类型(Primitive Type)

包装类(Wrapper Class)

存储位置

栈内存(直接存储数值)

堆内存(存储对象引用,对象包含数值)

默认值

0

null

内存占用

4 字节

约 16 字节(对象头 + 成员变量 + 对齐填充)

使用场景

场景

int

Integer

泛型与集合

不能直接使用(需装箱为 Integer)

可直接用于集合(如 List)

数据库映射

无法表示 NULL(可能引发歧义)

可表示 NULL(与数据库字段对应更准确)

方法参数与返回值

传递值(无法为 null)

传递对象引用(可为 null)

自动装箱与拆箱

Java 5+ 引入自动装箱(Autoboxing)和拆箱(Unboxing)机制:

装箱:int → Integer(隐式调用 Integer.valueOf())

Integer a = 10; // 等价于 Integer.valueOf(10)

拆箱:Integer → int(隐式调用 Integer.intValue())

int b = a; // 等价于 a.intValue()

比较操作

  • int 的比较:直接比较数值
int x = 1000, y = 1000;
System.out.println(x == y); // true(值相等)
  • Integer 的比较:需注意缓存机制(-128 到 127 有缓存)
Integer a = 127, b = 127;
System.out.println(a == b); // true(缓存范围内,引用相同)
Integer c = 128, d = 128;
System.out.println(c == d); // false(超出缓存范围,引用不同)
  • 建议:用 equals() 或 intValue() 比较值:
c.equals(d); // true(比较值)
c.intValue() == d; // true(拆箱后比较)

性能差异

  • int:性能更高(无需对象创建和垃圾回收)
  • Integer:性能较低(对象创建和拆装箱可能带来开销)

总结

选择依据

优先用 int

优先用 Integer

是否需要 null

不需要(如计算、临时变量)

需要(如数据库字段、API 返回值可为空)

是否涉及泛型/集合

不支持

必须使用

性能敏感场景

高性能计算、大规模数据存储

非性能关键路径(如业务逻辑层)

代码示例

// int 的默认值
int primitiveInt; // 默认值为 0
// Integer 的默认值
Integer wrapperInt; // 默认值为 null
// 装箱与拆箱
Integer num1 = 100; // 自动装箱
int num2 = num1; // 自动拆箱
// 缓存范围测试
Integer a = 100, b = 100;
System.out.println(a == b); // true(缓存内)
Integer c = 200, d = 200;
System.out.println(c == d); // false(缓存外)
最近发表
标签列表