patternjavaModerate
Returning an array containing values from two passed in arrays
Viewed 0 times
containingarraysarraypassedtworeturningvaluesfrom
Problem
This is a simple piece of code which takes two arrays supplied as parameters, then appends them to a new array that contains the values from the supplied arrays. Any suggestions for improvement would be greatly appreciated.
public static int[] append(int[] list1, int[] list2) {
int[] appendedList = new int[list1.length + list2.length];
for(int i = 0; i < list1.length; i++) {
appendedList[i] = list1[i];
}
for(int i = 0; i < list2.length; i++) {
appendedList[i + list1.length] = list2[i];
}
return appendedList;
}Solution
You could offload some of the work to
Arrays.copyOf and System.arraycopy:public static int[] append(int[] first, int[] second) {
int[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}Code Snippets
public static int[] append(int[] first, int[] second) {
int[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}Context
StackExchange Code Review Q#94398, answer score: 12
Revisions (0)
No revisions yet.