笔友城堡 - 可定义的个人主页

前言

在Java面试中,intInteger之前的区别是经常被问的,其两个本质上是完全不同:一个是基本数据类型,一个是包装类

下面记录一下,方便自己查看。

正文

区别

对比点intInteger
类型基本数据类型引用类型
是否为对象❌ 否✅ 是
默认值0null
存储位置栈(局部变量)堆(对象)
能否为 null❌ 不能✅ 可以
是否支持泛型❌ 不支持✅ 支持
内存占用更小更大(对象头 + 字段)
常用场景计算、循环、性能敏感集合、反射、泛型

自动装箱 & 拆箱

  1. 自动装箱(Boxing)

    Integer i = 100;  
    // 编译后等价于:
    Integer i = Integer.valueOf(100);
  2. 自动拆箱(Unboxing)

    Integer i = 100;
    int n = i;  
    // 编译后等价于:
    int n = i.intValue();
  3. 空指针风险

    Integer i = null;
    int n = i;   // NullPointerException

Integer 缓存机制

Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true

Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false

原因:

  1. Integer.valueOf()会缓存 [-128, 127] 范围内的对象:

    public static Integer valueOf(int i) {
        if (i >= -128 && i <= 127)
            return IntegerCache.cache[i + 128];
        return new Integer(i);
    }
  2. == 比较的是对象地址

  3. equals() 永远比较数值

    equals() 永远比较数值

int 与 Integer 的比较规则

比较方式结果说明
int == int比较值
int == IntegerInteger 自动拆箱,比较值
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

为什么需要 Integer?

泛型必须使用引用类型
List<int> list;     // ❌ 编译错误
List<Integer> list; // ✅
集合框架只存对象
Map<String, Integer> map;
允许 null 表示“无值”
Integer age = null; // 合法
int age = null;     // ❌ 非法

性能建议

优先使用int
  • 循环

  • 计数

  • 数学运算

使用Integer

  • 数据库字段可为空
  • JSON / DTO
  • 集合、泛型

总结

  1. int 是基本类型,效率高但不能为 null;

  2. Integer 是包装类,功能强但开销大,常用于集合和泛型

参考文章

AI

相关网址

笔友城堡 - 可定义的个人主页

暂无评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

none
暂无评论...