Java-数组
数组的初始化方式:
1.直接初始化
int [] array= {12,24,435};
// a.array存放的是数组地址并非其本身
// b.内存连续
// c.存到数组中的数据类型均为int
// 注:“=”左边称为“数组声明”;“=”右边称为“数组初始化”。
//必须在声明数组时一起使用,例:
// String [] names;
// names = {"Tim","John","Jack"};//这样写就为错误用法!
2.进行数组实例化
String [] address1 = new String[] {"河南省郑州市","北京"};
//此为“数组的实例化”,可以分开写,例如:
String [] address2;
address2 = new String[] {"河南省郑州市","北京"};
//也为正确写法
数组的遍历方式:
for (集合中元素数据类型 元素名 : 数组名) {
}
一维数组:
int [] scores= {100,90,80,70,60};
for(int score:scores) {
System.out.println(score);
}//遍历一位数组
结果:
100
90
80
70
60
二维数组:
String [][] names;
names = new String[][] {{"Jack","Tom","John"},{"Make","Jim"},{"Tim"}};
for(String[] names0:names) {
for(String name:names0) {
System.out.println(name);
}
}
结果:
Jack
Tom
John
Make
Jim
Tim
值传递与引用传递:
值传递(pass by value)是指在调用函数时将实际参数复制 一份传递到函数中,这样在函数中如果对 参数 进行修改,将不会影响到实际参数。
public class Test {
public static void main(String[] args) {
int x=10;
test(x);
System.out.println(x);//输出10
}
public static void test(int y) {
y=0;
}
//仅将x的值传递给y,当y改变时,x不变
}
引用传递(pass by reference)是指在调用函数时将实际参数的地址 直接 传递到函数中,那么在函数中对 参数 所进行的修改,将影响到实际参数。
public class Test {
public static void main(String[] args) {
int [] x= {10};
test(x);
System.out.println(x[0]);//输出0
}
public static void test(int [] y) {
y[0]=0;
}
//将x数组的地址传递给y数组,当y数组改变时,x数组也随之变化
}