博查AI搜索
博查是一个无广告干扰的答案引擎。你可以用自然语言提问,它会理解问题、细分检索并生成准确的答案。
在Java面试中,int和Integer之前的区别是经常被问的,其两个本质上是完全不同:一个是基本数据类型,一个是包装类。
下面记录一下,方便自己查看。
| 对比点 | int | Integer |
|---|---|---|
| 类型 | 基本数据类型 | 引用类型 |
| 是否为对象 | ❌ 否 | ✅ 是 |
| 默认值 | 0 | null |
| 存储位置 | 栈(局部变量) | 堆(对象) |
| 能否为 null | ❌ 不能 | ✅ 可以 |
| 是否支持泛型 | ❌ 不支持 | ✅ 支持 |
| 内存占用 | 更小 | 更大(对象头 + 字段) |
| 常用场景 | 计算、循环、性能敏感 | 集合、反射、泛型 |
自动装箱(Boxing)
Integer i = 100; // 编译后等价于: Integer i = Integer.valueOf(100);
自动拆箱(Unboxing)
Integer i = 100; int n = i; // 编译后等价于: int n = i.intValue();
空指针风险
Integer i = null; int n = i; // NullPointerException
Integer a = 127; Integer b = 127; System.out.println(a == b); // true Integer c = 128; Integer d = 128; System.out.println(c == d); // false
原因:
Integer.valueOf()会缓存 [-128, 127] 范围内的对象:
public static Integer valueOf(int i) { if (i >= -128 && i <= 127) return IntegerCache.cache[i + 128]; return new Integer(i); }
== 比较的是对象地址
equals() 永远比较数值
equals() 永远比较数值| 比较方式 | 结果说明 |
|---|---|
| int == int | 比较值 |
| int == Integer | Integer 自动拆箱,比较值 |
| Integer == Integer | 比较引用地址 |
| Integer.equals(Integer) | 比较数值 |
示例:
int a = 100; Integer b = 100; Integer c = new Integer(100); System.out.println(a == b); // true System.out.println(a == c); // true System.out.println(b == c); // false System.out.println(b.equals(c)); // true
List<int> list; // ❌ 编译错误 List<Integer> list; // ✅
Map<String, Integer> map;Integer age = null; // 合法 int age = null; // ❌ 非法
循环
计数
数学运算
int 是基本类型,效率高但不能为 null;