int 和 Integer 都是 Java 中的整数类型,但它们有一些关键的区别:
- int 是基本类型,Integer 是包装类类型(java.lang.Integer)。
- int 变量直接存储整数值,Integer 变量存储 Integer 对象的引用。
- int 的默认值是 0,Integer 的默认值是 null。
- Integer 类有很多有用的方法,比如解析字符串为整数(parseInt),整数与字符串的转换(toString),等等。int 作为基本类型没有这些方法。
- Integer 对象在内存中占用更多空间,因为它存储对象头信息和整数值。int 只存储值。
- 装箱和拆箱:给 int 变量赋值 Integer 对象,会自动装箱,反之亦然,这需要消耗一定资源。
例子:
int x = 5; // 基本类型
Integer y = new Integer(5); // 包装类
// 装箱,将 int 转换为 Integer
Integer a = x;
// 拆箱,将 Integer 转换为 int
int b = y;
// Integer 类方法
String s = y.toString();
int z = Integer.parseInt(s);
所以,如果不需要 Integer 类提供的方法,并且性能要求较高,优先选择 int。如果需要使用包装类的方法,或者在泛型中使用,选择 Integer 。