Java 示例 - 扩展数组
-
问题描述
初始化后如何扩展数组? -
解决方案
以下示例显示了如何在初始化后通过创建新数组来扩展数组。public class Main { 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.println(str); } } }
-
结果
上面的代码示例将产生以下结果。A B C D E
以下是数组扩展的另一个示例示例public class Main { public void extendArraySize() { String[] names = new String[] {"Sai", "Ram", "Krishna"}; String[] extended = new String[5]; extended[3] = "Prasad"; extended[4] = "Mammahe"; System.arraycopy(names, 0, extended, 0, names.length); for (String str : extended) System.out.println(str); } public static void main(String[] args) { new Main().extendArraySize(); } }
上面的代码示例将产生以下结果。Sai Ram Krishna Prasad Mammahe