Tuesday, March 28, 2006
Put Three Arrays Into One With Java
Ever since I learned about Vector in Java 1.0 I never wanted to touch an array again. But I had to today. I needed to concatenate three arrays into one. Here is a non-obvious elegant way:
System.arraycopy(array1, 0, finalArray, 0, array1.length);
System.arraycopy(array2, 0, finalArray, array1.length, array2.length);
System.arraycopy(array3, 0, finalArray, (array1.length+array2.length), array3.length);
That sure beats a bunch of for loops.
System.arraycopy(array1, 0, finalArray, 0, array1.length);
System.arraycopy(array2, 0, finalArray, array1.length, array2.length);
System.arraycopy(array3, 0, finalArray, (array1.length+array2.length), array3.length);
That sure beats a bunch of for loops.
Comments:
<< Home
It was legacy code that I had to update in a place where someone should have been using ArrayLists instead. I figured it would be easier to do this change than redo a whole API interface. This part of the API is on the TODO list for a refactoring to collections.
Post a Comment
<< Home