public class StringConcatenate {
public static void main(String[] args){
// Create two arrays to concatenate and one array to hold bothString[] arr1 = new String[]{"s","t","r","i","n","g"};String[] arr2 = new String[]{"s","t","r","i","n","g"};String[] arrBoth = new String[arr1.length+arr2.length];
// Copy elements from first array into first part of new arrayfor(int i = 0; i < arr1.length; i++){arrBoth[i] = arr1[i];}
// Copy elements from second array into last part of new arrayfor(int j = arr1.length;j < arrBoth.length;j++){arrBoth[j] = arr2[j-arr1.length];}
// Print resultfor(int k = 0; k < arrBoth.length; k++){System.out.print(arrBoth[k]);}
// Additional line to make your terminal look better at completion!System.out.println();}}
public static class Array {
public static <T> T[] concat(T[]... arrays) {ArrayList<T> al = new ArrayList<T>();for (T[] one : arrays)Collections.addAll(al, one);return (T[]) al.toArray(arrays[0].clone());}}
List<String> myList = new ArrayList<String>(Arrays.asList(first));myList.addAll(new ArrayList<String>(Arrays.asList(second)));String[] both = myList.toArray(new String[myList.size()]);
// I have arrayA and arrayB; would like to treat them as concatenated// but leave my damn bytes where they are!Object accessElement ( int index ) {if ( index < 0 ) throw new ArrayIndexOutOfBoundsException(...);// is reading from the head part?if ( index < arrayA.length )return arrayA[ index ];// is reading from the tail part?if ( index < ( arrayA.length + arrayB.length ) )return arrayB[ index - arrayA.length ];throw new ArrayIndexOutOfBoundsException(...); // index too large}
public static String[] mergeArrays(String[] array1, String[] array2) {int totalSize = array1.length + array2.length; // Get total sizeString[] merged = new String[totalSize]; // Create new array// Loop over the total sizefor (int i = 0; i < totalSize; i++) {if (i < array1.length) // If the current position is less than the length of the first array, take value from first arraymerged[i] = array1[i]; // Position in first array is the current position
else // If current position is equal or greater than the first array, take value from second array.merged[i] = array2[i - array1.length]; // Position in second array is current position minus length of first array.}
return merged;
用法:
String[] array1str = new String[]{"a", "b", "c", "d"};String[] array2str = new String[]{"e", "f", "g", "h", "i"};String[] listTotalstr = mergeArrays(array1str, array2str);System.out.println(Arrays.toString(listTotalstr));
public static int[] combineArrays(int[] a, int[] b) {int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {c[i] = a[i];}
for (int j = 0, k = a.length; j < b.length; j++, k++) {c[k] = b[j];}
return c;}
public static <T> T[] arrayConcat(T[] a, T[] b) {T[] both = Arrays.copyOf(a, a.length + b.length);System.arraycopy(b, 0, both, a.length, b.length);return both;}
String[] a = new String[] { "a", "b", "c", "d" };String[] b = new String[] { "e", "f", "g", "h" };String[] c = new String[] { "i", "j", "k", "l" };
concat( a, b, c ); // [a, b, c, d, e, f, g, h, i, j, k, l]
public String[] concat(String[] firstArr,String[] secondArr){//if both is empty just returnif(firstArr.length==0 && secondArr.length==0)return new String[0];
String[] res = new String[firstArr.length+secondArr.length];int idxFromFirst=0;
//loop over firstArr, idxFromFirst will be used as starting offset for secondArrfor(int i=0;i<firstArr.length;i++){res[i] = firstArr[i];idxFromFirst++;}
//loop over secondArr, with starting offset idxFromFirst (the offset track from first array)for(int i=0;i<secondArr.length;i++){res[idxFromFirst+i]=secondArr[i];}
return res;}
static <T> T[] concatWithCollection(T[] array1, T[] array2) {List<T> resultList = new ArrayList<>(array1.length + array2.length);Collections.addAll(resultList, array1);Collections.addAll(resultList, array2);
@SuppressWarnings("unchecked")//the type cast is safe as the array1 has the type T[]T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0);return resultList.toArray(resultArray);}
测试
@Testpublic void givenTwoStringArrays_whenConcatWithList_thenGetExpectedResult() {String[] result = ArrayConcatUtil.concatWithCollection(strArray1, strArray2);assertThat(result).isEqualTo(expectedStringArray);}
public static <T> T concat(T a, T b) {//Handles both arrays of Objects and primitives! E.g., int[] out = concat(new int[]{6,7,8}, new int[]{9,10});//You get a compile error if argument(s) not same type as output. (int[] in example above)//You get a runtime error if output type is not an array, i.e., when you do something like: int out = concat(6,7);if (a == null && b == null) return null;if (a == null) return b;if (b == null) return a;final int aLen = Array.getLength(a);final int bLen = Array.getLength(b);if (aLen == 0) return b;if (bLen == 0) return a;//From here on we really need to concatenate!
Class componentType = a.getClass().getComponentType();final T result = (T)Array.newInstance(componentType, aLen + bLen);System.arraycopy(a, 0, result, 0, aLen);System.arraycopy(b, 0, result, aLen, bLen);return result;}
public static void main(String[] args) {String[] out1 = concat(new String[]{"aap", "monkey"}, new String[]{"rat"});int[] out2 = concat(new int[]{6,7,8}, new int[]{9,10});}
/*** With Java Streams* @param first First Array* @param second Second Array* @return Merged Array*/String[] mergeArrayOfStrings(String[] first, String[] second) {return Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(String[]::new);}