Adding 2 Java arrays in 4 lines.
First, and foremost, do your damndest to avoid the use of primitives. If you're in the 21st century anyway, we have higher level languages and those languages have objects and, hot damn, let you make objects - so use them!!!
Be assured you'll hear more from me on that front for a long time to come. Anyhoo though...
This quick post is about when you, for one legit reason or another, do have to work with primitive Java arrays. As in "String[]" array, not "ArrayList<String>".
Today, Gil and I had to and were quite miffed to find there was no easy built in way to combine to existing arrays. Once the disgust was gone enough to type again, we coded a little utility to do it.
So, here's what we ended up with:
Do note please that this creates a third array which is thus returned (as opposed to actually changing the state of either one of the input arrays).
public static String[] arrayAdd(String[] one, String[] two) {
String[] newArray = new String[one.length + two.length];
System.arraycopy(one, 0, newArray, 0, one.length);
System.arraycopy(two, 0, newArray, one.length, two.length);
return newArray;
}
If you've got better suggestions (libraries, whatever), shout em out. Otherwise, enjoy.
And, yes, of course, we do have a test for that!
ps// can't help it. To reassert my initial point, "resist your primitive obsession", using a List (object), of course, you get:
public static List<String> listAdd(List<String> one, List<String> two) {
List<String> newList = new ArrayList<String>();
newList.addAll(one);
newList.addAll(two);
return newList;
}
..and then of course if you don't want a new collection instance:
one.addAll(two);
Hi there, got to your blog via Cory Haines' one...started reading your latest post, then worked my way down through the one on Killing Quality, then the TDD ones...quality stuff, then I hit this post and because I haven't been coding much lately, I had an itch to scratch, and thought I'd take up the challenge...I found that in JDK 1.6, the Arrays class now provides a 'copyOf' method that allows you to shorten your method (I made the method generic as well):
ReplyDeletepublic static <T> T[] arrayAdd(T[] one, T[] two)
{
T[] newArray = Arrays.copyOf(one, one.length + two.length );
System.arraycopy(two, 0, newArray, one.length, two.length);
return newArray;
}
Hi Philip --
ReplyDeleteVery glad you're finding my blog useful. Thanks for saying! More to come, stay tuned ;-)
So, as for your find with JDK 6 - super! Thanks for posting that up here for others (and myself) to leverage.
Cheers
MB