目录
在声明数组的同时初始化数组。
你可以在声明数组的同时初始化它,方法如下:
示例代码
static void arraySample() { String[] s = {"apple", "orange", "banana"}; } System.out.println(s[1]);
输出结果:
橘子
获取数组中元素的数量。 尺寸
要获取数组中元素的数量,请使用 `length` 函数。请注意,`length` 是一个字段,而不是一个方法。
示例代码
static void lengthSample() {
String[] s1 = {"りんご", "みかん", "ぶどう"};
String[] s2 = {};
System.out.println(s1.length);
System.out.println(s2.length);
}
输出结果:
3 0
复制数组 – 克隆
如果你想创建一个与另一个数组完全相同的数组,`clone` 命令就很有用。
示例代码
static void cloneSample() { String[] s1 = {"apple", "orange", "grape"}; String[] s2 = s1.clone(); System.out.println(s1[0] + ' ' + s1[1] + ' ' + s1[2]); System.out.println(s2[0] + ' ' + s2[1] + ' ' + s2[2]); }
输出结果:
苹果、橙子、葡萄、苹果、橙子、葡萄
复制数组 – 系统.数组复制
Java 数组的大小在初始化时就已固定。如果想在数组创建后增加其大小,需要使用 System.arraycopy 方法。
`arraycopy` 用于复制数组,就像 `clone` 一样,但它允许比 `clone` 更详细的配置。
arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src... 要复制的数组 srcPos... 从源数组 (src) 复制的起始位置 dest... 目标数组 destPos... 从目标数组 (dest) 复制的起始位置 length... 要复制的元素数量
示例代码
static void arraycopySample() { String[] s1 = {"apple", "orange", "grape"}; String[] s2 = new String[5]; System.arraycopy(s1, 0, s2, 0, 3); s2[3] = "banana"; s2[4] = "cherry"; System.out.println(s1[0] + " " + s1[1] + " " + s1[2]); System.out.println(s2[0] + " " + s2[1] + " " + s2[2] + " " + s2[3] + " " + s2[4]); }
输出结果:
苹果、橙子、葡萄、苹果、橙子、葡萄、香蕉、樱桃
ArrayCopy 在连接数组时也很有用。
示例代码
static void joinArraySample() {
String[] s1 = {"りんご", "みかん", "ぶどう"};
String[] s2 = {"ばなな", "さくらんぼ", "もも"};
int rLen = s1.length + s2.length;
String[] rStr = new String[rLen]; //s1とs2両方の長さ分の配列を初期化
System.arraycopy(s1, 0, rStr, 0, s1.length);
System.arraycopy(s2, 0, rStr, s1.length, s2.length); //コピー先配列の開始位置の設定がポイント
System.out.println(rStr[0] + " " + rStr[1] + " " + rStr[2] + " " + rStr[3] + " " + rStr[4] + " " + rStr[5]);
}
输出结果:
苹果、橙子、葡萄、香蕉、樱桃、桃子
创建一个多维数组
通过在另一个数组中创建数组,您可以创建一个多维数组。例如,这在存储表格数据时非常有用。
示例代码
static void twoDArraySample() { int[] a1 = {38, 84, 98}; int[] a2 = {32, 11, 56}; int[] a3 = {82, 77, 8}; int[][] twoDArray = {a1, a2, a3}; for (int[] a : twoDArray) { for (int score : a) { System.out.print(score + " "); } System.out.println(""); } }
输出结果:
38 84 98 32 11 56 82 77 8
