8、值传递和引用传递
# 引用数据类型
既然你知道对象的创建了,结合数组的章节,来看一下回顾一下数据类型。
Java数据类型中,分为基本数据类型和引用数据类型
常见的引用数据类型就是类和数组了。
# eg:
class HaC {
String name;
public static void main(String[] args) {
int age = 25;
String[] interests = {"打代码"};
int[] scores ={100};
HaC haC = new HaC();
haC.name = "HaC";
System.out.println("我的名字:" + haC.name + ",年龄:" + age + ",我的兴趣之一:" + interests[0] + ",分数:" + scores[0]);
changeName(haC);
changeAge(age);
changeInterests(interests);
changeScores(scores);
System.out.println("-----修改后------");
System.out.println("我的名字:" + haC.name + ",年龄:" + age + ",我的兴趣之一:" + interests[0] + ",分数:" + scores[0]);
}
static void changeName(HaC haC) {
haC.name = "哈C";
}
static void changeAge(int age) {
age = 18;
}
static void changeInterests(String interests[]) {
interests[0] = "开车";
}
static void changeScores(int scores[]) {
int[] newScores ={60};
scores = newScores;
}
}
输出:
我的名字:HaC,年龄:25,我的兴趣之一:打代码,分数:100
-----修改后------
我的名字:哈C,年龄:25,我的兴趣之一:开车,分数:100
可以看到有两处修改成功了:
haC.name = "哈C"; interests[0] = "开车";
而 age
、scores[]
没有修改成功。
在Java中,大家都觉得参数的传递分为 值传递 和 引用传递
如果参数是基本类型,传递的是基本类型的字面量值的拷贝。 如果参数是引用类型,传递的是该参量所引用的对象在堆中地址值的拷贝。
但是Java中方法参数传递方式是按值传递,也只有值传递(地址也是值啊!)
图解:
# 1、 changeName 、changeInterests 的原理是一样的
# 1)第一步
HaC haC = new HaC();
haC.name = "HaC";
haC
是一个引用地址0x9527
,指向 new HaC()
对象
# 2)第二步
调用方法
changeName(haC);
static void changeName(HaC haC) {
}
HaC haC = new HaC();
和 changeName(HaC haC)
参数里面的两个haC
地址都是一样的,指向同一个对象。
# 3)第三步
修改
haC.name = "哈C";
所以这个修改是通过地址去修改了值。
# 2、changeAge、changeScores 原理差不多
changeAge的过程:
int age = 25;
changeAge(age);
把age
的值copy 了一份给changeAge
方法
修改了进行修改(但是这个修改是修改副本的值)
age = 18;
changeScores 的过程:
# 1)第一步
初始化
int[] scores ={100};
scores
指向一个地址0x1314
# 2、第二步
调用方法
changeScores(scores);
static void changeScores(int scores[]) {
}
把scores
的地址传递给副本(方法),两个同样指向地址0x1314
# 3、第三步
changeScores
方法重新把一个新值(地址)赋予给scores
int[] newScores ={60};
scores = newScores;
此时两个地址是不一样的,但是方法里面的局部变量scores
和 全局变量 scores
所指向的是不一样的,你是你,我是我。
上次更新: 2025-02-21 06:04:57