2018/1/26
java
1.关于java中传引的介绍
package swap;
public class class1 {
public static void main(String[] args) {
Demo demo = new Demo();//在堆内存中开辟一个空间,并且把地址传递给demo
{
swap(demo);//引用传递,传递的是一个地址
System.out.println(demo.num1 + " " + demo.num2);
}
}
static class Demo
{
int num1 = 10;
int num2 = 50;
}
/*答案为50 10*/
public static void swap(Demo demo) {
int temp;
temp = demo.num1;
demo.num1 = demo.num2;
demo.num2 = temp;
}
}
package swap;
import swap.class1.Demo;
public class class2 {
public static void main(String[] args) {
Demo demo = new Demo();//在堆内存中开辟一个空间,并且把地址传递给demo
{
swap(demo);//引用传递,传递的是一个地址
System.out.println(demo.num1 + " " + demo.num2);
}
}
static class Demo
{
int num1 = 10;
int num2 = 50;
}
/*答案为10 50*/
public static void swap(Demo demo) {
int temp;
demo = new Demo();/*重新给demo新的地址,覆盖了当前地址*/
temp = demo.num1;
demo.num1 = demo.num2;
demo.num2 = temp;
}
}
这两个程序样子很相像,但是为什么结果不同呢?
关键有一句,这就是传引的用法,因为在java中分为动态区和静态区,动态区在栈内存,表示时常修改,可变的区域,而在堆内存上,因为不常修改,称为静态区,
这句话的意思是:在堆内存中开辟一个空间给Demo,把Demo的地址给了demo,然后接下来swap(demo)就是对地址的操作,通过对地址的操作,实现了栈内存和堆内存的交流,就是所谓的传引.
Demo demo = new Demo();
2.关于装箱和拆箱的简单用法(boxing和unboxing)
在java中,自己设计的数据类型可以通过操作实例化称为对象来操作,在基本数据类型中要实现实例化对象,就要用拆箱和装箱来解决
int num1=10; int num2=20; /*装箱*/ Integer INUM1= Integer.valueOf(num1); Integer INUM1=new Integer(num1);
/*自动装箱*/Integer INUM2=num2;
/*拆箱*/ int num3=INUM1.intValue();
/*自动拆箱 */int num4=INUM2;
//比较两个数
System.out.println(INUM1.compareTo(INUM2));/*第一个数字大于第二个数字,返回1,等于返回0,小于返回-1*/
}