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.

Comments:
What situation were you in that made you need this multi-dimensional array?

Unless I'm creating a SOAP response I avoid these like American Idol.
 
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

Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?