Integer 和 int 的区别?
参考回答
Integer 和 int 的区别如下:
类型
int 是基本数据类型,存储的是数值。
Integer 是 int 的包装类,是一个对象,存储的是 int 值的引用。
内存分配
int 存储在栈中,效率高,直接存储数值。
Integer 是对象,存储在堆中,效率相对较低。
用途
int 用于基本的数值运算。
Integer 提供了更多功能,比如可以与集合类(List、Map 等)一起使用,因为集合类只能存储对象。
自动装箱和拆箱
Java 自动支持基本类型与其包装类之间的转换(自动装箱和拆箱)。
装箱:int 转换为 Integer。
拆箱:Integer 转换为 int。
详细讲解与拓展
1. 定义和使用
int 示例:
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = a + b;
System.out.println(“Sum: ” + c); // 输出:Sum: 30
}
}
Integer 示例:
public class Main {
public static void main(String[] args) {
Integer a = 10;
Integer b = 20;
Integer c = a + b; // 自动拆箱后再运算
System.out.println(“Sum: ” + c); // 输出:Sum: 30
}
}
2. 自动装箱和拆箱
从 Java 5 开始,Java 提供了自动装箱和拆箱功能:
装箱(Boxing):
将基本类型 int 转换为包装类 Integer。
拆箱(Unboxing):
将包装类 Integer 转换为基本类型 int。
示例代码:
public class Main {
public static void main(String[] args) {
int a = 10;
Integer b = a; // 自动装箱
int c = b; // 自动拆箱
System.out.println(“Integer: ” + b); // 输出:Integer: 10
System.out.println(“int: ” + c); // 输出:int: 10
}
}
3. 内存分配
int:
存储在栈内存中,直接保存值,效率高。
Integer:
是一个对象,存储在堆内存中,包含元数据(如值和方法),占用更多内存。
- Integer 缓存机制
Java 对于 -128 到 127 之间的 Integer 对象进行了缓存。
当值在该范围内时,会直接返回缓存中的对象。
如果值超出范围,会创建新的对象。
示例代码:
public class Main {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer c = 200;
Integer d = 200;
System.out.println(a b); // true,使用缓存
System.out.println(c d); // false,超出缓存范围
}
}
输出结果:
true
false
5. 与集合的结合使用
int 不能直接存储在集合中,必须使用 Integer。
示例代码:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList
list.add(10); // 自动装箱
list.add(20);
int sum = 0;
for (Integer num : list) {
sum += num; // 自动拆箱
}
System.out.println(“Sum: ” + sum); // 输出:Sum: 30
}
}
主要区别对比
特性 int Integer
类型 基本数据类型 引用类型(包装类)
内存 栈内存 堆内存
用途 基本数值运算 用于集合、对象操作
性能 高,直接操作数值 低,需要拆装箱或额外的内存
多功能性 无 提供多种方法(如 toString、parseInt)
缓存范围 不适用 -128 到 127 之间有缓存
拓展知识
1. Integer 的常用方法
parseInt(String s):将字符串转为 int。
valueOf(String s):将字符串转为 Integer 对象。
toString():将 Integer 转为字符串。
示例代码:
public class Main {
public static void main(String[] args) {
String str = “123”;
int number = Integer.parseInt(str); // 字符串转 int
Integer integer = Integer.valueOf(str); // 字符串转 Integer
System.out.println(“Number: ” + number); // 输出:123
System.out.println(“Integer: ” + integer); // 输出:123
}
}
2. 注意 和 equals() 的区别
比较的是引用地址,只有当两个 Integer 对象引用相同时才返回 true。
equals() 比较的是值。
示例代码:
public class Main {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer c = 200;
Integer d = 200;
System.out.println(a b); // true,使用缓存
System.out.println(c d); // false,超出缓存范围
System.out.println(c.equals(d)); // true,值相同
}
}
3. Integer 与 Double 的比较问题
Integer 和 Double 不能直接比较,会有类型转换问题。
必须通过拆箱转为 int 或 double 后再比较。
总结
int 是基础类型,效率高,用于基本的数值运算。
Integer 是包装类,适合与集合和对象操作,提供了更多实用方法。
在实际开发中,选择 int 还是 Integer,要根据场景需求(性能 vs 多功能性)权衡选择。