本文只说明两个问题:
1.数组的对象性
2.数组的复制
1.数组的对象性
数组定义:
int[] scores = new int[10];
在java中只要看到new,一定就是建立对象,这个语法代表了数组就是对象。如果想查看初始值可以点击链接。
然而,对象是根据类而建立的实例,代表建立数组对象的类定义在哪里呢?答案是由JVM动态产生的。某种程度上,可以将int[]这样的写法,看做类名称。
例子:看看下面的代码会显示什么?
int[] scores1 = {88, 81, 74, 68, 76};
int[] scores2 = scores1;
scores2[0] = 99;
System.out.println(scores1[0]);
因为数组是对象,而scores1 和scores2 是对象名称,将scores1 赋值给scores2 ,意思是将scores1 的地址复制给scores2 ,即scores2 也指向该数组。
scores2[0] = 99 的意思是,将scores2 指向的数组的索引0的值设置为99,因此无论谁调用,索引0的元素的值都会是99。
2.数组的复制
了解数组是对象,应该知道,以下代码不是数组复制:
int[] scores1 = {88, 81, 74, 68, 76};
int[] scores2 = scores1;
其作用只不过是将scores1 的地址复制给scores2 。如果要做数组复制,基本做法是另行建立数组,例如:
int[] scores1 = {88, 81, 74, 68, 76};
int[] scores2 = new int[scores1.length];
for(int i = 0; i < scores1.length; i++){
scores2[i] = scores1[i];
}
通过建立长度相同的数组,逐一访问scores1每个元素,并指定给scores2对应的索引位置。
其实,有更方便的Arrays.copyOf( )方法:
import java.util.Arrays;
public class CopyArray {
public static void main(String[] args) {
int[] scores1 = { 88, 81, 74, 68, 76 };
// 不用新建数组,Arrays.copyOf()会帮你建立
int[] scores2 = Arrays.copyOf(scores1, scores1.length);
for (int i = 0; i < scores2.length; i++) {
System.out.print(scores2[i] + "\t");
}
System.out.println();
scores2[0] = 99;
// 不影响scores1指向的数组对象
for (int i = 0; i < scores2.length; i++) {
System.out.print(scores1[i] + "\t");
}
}
}
输出结果为
88 81 74 68 76
88 81 74 68 76
3.在java中,数组一旦建立,长度就固定了。如果事先建立的数组长度不够怎么办?那就只好建立新数组,将原数组内容复制到新数组。例如:
// 如果数组长度不够了,就需要建立新数组,将原数组内容复制至新数组
int[] score1 = { 88, 81, 74, 68, 76 };
int[] score2 = Arrays.copyOf(score1, score1.length * 2);
score2[score1.length] = 99;
for (int i = 0; i < score2.length; i++) {
System.out.print(score2[i] + "\t");
}
输出结果为:
88 81 74 68 76 99 0 0 0 0