使用for循环添加另一个字符串数组

Man*_*nju 1 java android

嗨,我使用for循环来添加数组中的字符串.任何人都可以帮助我下面的代码显示错误.

image = new String[] {"APP","FIELD","KYC"};

image2 = new String[] {"MEMORANDUM","ASSOCIATION"};
Run Code Online (Sandbox Code Playgroud)

现在使用for循环或任何方法我需要相同的图像数组

image = new String[] {"APP","FIELD","KYC","MEMORANDUM","ASSOCIATION"};
Run Code Online (Sandbox Code Playgroud)

Pan*_*mar 6

是的,这可以没有循环.使用ArrayUtils.addAll(T [],T ...)

String[] both = ArrayUtils.addAll(image, image2);
Run Code Online (Sandbox Code Playgroud)

这是一个带有数组List转换/ 转换的解决方案.

String[] image = new String[] {"APP","FIELD","KYC"};
String[] image2 = new String[] {"MEMORANDUM","ASSOCIATION"};
List<String> list = new ArrayList<String>(Arrays.asList(image));
list.addAll(Arrays.asList(image2));
String[] result = list.toArray(new String[]{});
System.out.println(Arrays.toString(result));
Run Code Online (Sandbox Code Playgroud)

输出将与您要求的输出相同.


正如梅纳建议的另一个解决方案可以是System.arraycopy

String[] image = new String[] {"APP","FIELD","KYC"};
String[] image2 = new String[] {"MEMORANDUM","ASSOCIATION"};
String[] result = new String[image.length + image2.length]; 

// copies an array from the specified source array
System.arraycopy(image, 0, result, 0, image.length);
System.arraycopy(image2, 0, result, image.length, image2.length);

// Now you can use result for final array
Run Code Online (Sandbox Code Playgroud)

阅读更多关于如何在Java中连接两个数组?