在Java中,数组初始化后如何扩展数组?
示例
以下示例显示如何在创建新并初始化数组后扩展数组。
package com.yiibai;
public class ExtendingArray {
public static void main(String[] args) {
String[] names = new String[] { "A", "B", "C" };
String[] extended = new String[5];
extended[3] = "D";
extended[4] = "E";
System.arraycopy(names, 0, extended, 0, names.length);
for (String str : extended) {
System.out.print(str+",");
}
}
}
执行上面示例代码,得到以下结果 -
A,B,C,D,E,
示例2
以下是数组扩展的另一个示例示例 -
package com.yiibai;
public class ExtendingArray2 {
public void extendArraySize() {
String[] names = new String[] { "Maxsu", "Minsu", "Sum" };
String[] extended = new String[5];
extended[3] = "Sukida";
extended[4] = "Avg";
System.arraycopy(names, 0, extended, 0, names.length);
for (String str : extended)
System.out.println(str);
}
public static void main(String[] args) {
new ExtendingArray2().extendArraySize();
}
}
执行上面示例代码,得到以下结果 -
Maxsu
Minsu
Sum
Sukida
Avg