package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 数组合并
* */
public class ArrayCombine {
/**
* 两个字符串数组的合并
* */
public void arrayCombine1(){ //不行
String[] str1 = {"a","b","e"};
String[] str2 = {"e","3","w"};
List arr1List = Arrays.asList(str1);
List arr2List = Arrays.asList(str2);
List list = new ArrayList();
list.addAll(arr1List);
list.addAll(arr2List);
Object[] arr3 = list.toArray();
for(Object obj : arr3){
System.out.println(obj);
}
}
/**
* 两个整形数组合并
* */
public void arrayCombine2(){
int[] arr1 = {1,3,4,6,8};
int[] arr2 = {23,4,2,14,54};
int[] arr3 = new int[arr1.length+arr2.length];
System.arraycopy(arr1, 0, arr3, 0, arr1.length);
System.arraycopy(arr2, 0, arr3, arr1.length, arr2.length);
}
/**
* 两个字符串类型数组合并
* */
public void arrayCombine3(){
String[] str1 = {"a","b","e"};
String[] str2 = {"e","3","w"};
String[] str3 = new String[str1.length + str2.length];
System.arraycopy(str1, 0, str3, 0, str1.length);
System.arraycopy(str2, 0, str3, str1.length, str2.length);
for(String s : str3){
System.out.println(s);
}
}
public static void main(String[] args) {
ArrayCombine ac = new ArrayCombine();
ac.arrayCombine1();
}
}
在用Arrays和Collection的addAll方法实现数组的合并的时候要主要对于基本数据类型不能使用这种方式,用完Collection只支持引用数据类型,而用System的arraycopy()方法则是一种通用的解决办法,而且更加灵活。