Java包装类 和 值传递机制
2020-12-02 本文已影响0人
得力小泡泡
一.什么是包装类

Java中的基本数据类型没有方法和属性,而包装类就是为了让这些拥有方法和属性,实现对象化交互。

装箱:基本数据类型转换为包装类;
拆箱:包装类转换为基本数据类型。

二、三元运算的原理
对于Object o1 = true ? new Integer(1) : new Double(2.0);
先计算出new Integer(1)和new Double(2.0)的值,并且要求两个结果类型相同,变成了Object o1 = true ? 1.0 : 2.0;
public class MyTest5 {
@Test
public void test1(){
Object o1 = true ? new Integer(1) : new Double(2.0);
System.out.println(o1);//1.0
}
@Test
public void test2(){
Object o2;
if(true)
o2 = new Integer(1);
else
o2 = new Double(2.0);
System.out.println(o2);//1
}
}
三、Integer类型的性质
Integer
内部定义了IntegerCache
结构,IntegerCache
中定义了Integer[]
,保存了-128 ~ 127
范围的整。如果我们使用自动装箱的方式,给Integer
赋值的范围在-128 ~ 127
范围内,可以直接使用数组中的元素,不用再去new
了

@Test
public void test3(){
Integer i = new Integer(1);
Integer j = new Integer(2);
System.out.println(i == j);//false
Integer m = 1;
Integer n = 1;
System.out.println(m == n);//true
Integer x = 128;//相当于new了一个Integer对象
Integer y = 128;
System.out.println(x == y);//false
}
四、值传递机制
形参:方法定义时,声明的小括号内的参数
实参:方法调用时,实际传递给形参的数据
关于变量的赋值:
1、如果变量是基本数据类型,此时实参赋给形参的是实参真实存储的数据值
2、如果变量是引用数据类型,此时实参赋给形参的是实参存储数据的地址值
参数类型为:基础数据类型的底层原理
最后栈中元素会一个个pop出,最后main方法输出的是10和20

参数类型为:基础数据类型的底层原理
主函数的data和传进swap方法的data指向堆中是同一个地址,因此修改的是同一地址的元素,因此最后栈中元素会一个个pop出,最后main方法输出的是20和10
