Java 提供了俩个类型系统:基本类型、引用类型
使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们使用基本类型对象一样操作,就可以使用基本类型对应的包装类
4类8种如下图(可以百度)
基本数据类型与包装类:主要记住 Integer 和 Character
基本类型与对应的包装类对象之间,来回转换的过程称为“装箱”与“拆箱”
装箱:从基本数据类型转换为对应的包装类对象
拆箱:从包装类对象转换为对应的基本类型
这里以 Integer 包装类为例说明拆箱与装箱
装箱:基本数值 --> 包装对象
// 构造方法
Integer integer1 = new Integer(1);
// 静态方法
Integer integer3 = Integer.valueOf(1);
拆箱:包装对象 --> 基本数值
// 成员方法 Integer对象.intValue()
int i = integer1.intValue();
自动装箱与自动拆箱:基本类型的数据和包装类之间可以自动的相互转换(JDK1.5之后新特性)
/*
* 自动装箱:把int->包装类
* Integer in = 1; 等价于 Integer in = new Integer(1);
* */
Integer in = 1;
/*
* 自动拆箱:in 是包装类,先转为int 在计算
* in +3; 自动拆箱 in.intValue() +3 = 4
* in = in.intValue() +3 ; 自动装箱
* */
in = in + 3;
使用场景: ArrayList
ArrayList<Integer> list = new ArrayList<>();
list.add(1); // 自动装箱,等价于下面代码
list.add(new Integer(1));
int i = list.get(1);//自动拆箱,等价于下面代码
int i1 = list.get(1).intValue();
在Java中使用自动装箱与拆箱应当注意的问题 (含面试题)
对象相等比较:
public class AutoboxingTest {
public static void main(String args[]) {
// Example 1: == comparison pure primitive – no autoboxing
int i1 = 1;
int i2 = 1;
System.out.println("i1==i2 : " + (i1 == i2)); // true
// Example 2: equality operator mixing object and primitive
Integer num1 = 1; // autoboxing
int num2 = 1;
System.out.println("num1 == num2 : " + (num1 == num2)); // true
// Example 3: special case - arises due to autoboxing in Java
Integer obj1 = 1; // autoboxing will call Integer.valueOf()
Integer obj2 = 1; // same call to Integer.valueOf() will return same cached Object
System.out.println("obj1 == obj2 : " + (obj1 == obj2)); // true
// Example 4: equality operator - pure object comparison
Integer one = new Integer(1); // no autoboxing
Integer anotherOne = new Integer(1);
System.out.println("one == anotherOne : " + (one == anotherOne)); // false
}
}
/** Output:
i1==i2 : true
num1 == num2 : true
obj1 == obj2 : true
one == anotherOne : false
*/
// 基本类型 -> 字符串(String)
int i1 = 100;
String s1 = i1+"";
System.out.println(s1+200);
String integer = Integer.toString(100);
System.out.println(integer+200);
String s = String.valueOf(100);
System.out.println(s+200);
// 字符串(String)-> 基本类型
int i = Integer.parseInt(s1);
System.out.println(i-10);
// int a = Integer.parseInt("a"); //NumberFormatException
本文地址:https://blog.csdn.net/wanglei19891210/article/details/107081454
如对本文有疑问, 点击进行留言回复!!
【奥鹏作业答案库网】大工20春《应用统计》在线作业1【奥鹏作业答案】
网友评论