9

I'm wondering how I can concatenate 4 string arrays in Java.

There is a question about this already. How can I concatenate two arrays in Java?

But I tried to replicate it but it does not work for me.

This is what my code looks like:

Calling the method:

concatAll(jobs1, jobs2, jobs3, jobs4);

The method itself:

public String[] concatAll(String[] jobsA, String[] jobsB, String[] jobsC, String[] jobsD) {
 int totalLength = jobsA.length;
 for (String[] array : jobsD) {
 totalLength += array.length;
 }
 String[] result = Arrays.copyOf(jobsA, totalLength);
 int offset = jobsA.length;
 for (String[] array : jobsD) {
 System.arraycopy(array, 0, result, offset, array.length);
 offset += array.length;
 }
 return result;
}
asked Nov 17, 2012 at 23:11
2
  • I'm somewhat confused here. What is a sample input, and a sample output? Commented Nov 17, 2012 at 23:14
  • How did this not get closed? Double Duplicate Commented Nov 17, 2012 at 23:57

2 Answers 2

16

Putting aside things like checking if an array is null, you can create a general method for it and use it in your specific case, like this:

 public String[] concatAll(String[] jobsA, String[] jobsB, String[] jobsC, String[] jobsD) 
 {
 return generalConcatAll (jobsA, jobsB, jobsC, jobsD);
 }
 public String[] generalConcatAll(String[]... jobs) {
 int len = 0;
 for (final String[] job : jobs) {
 len += job.length;
 }
 final String[] result = new String[len];
 int currentPos = 0;
 for (final String[] job : jobs) {
 System.arraycopy(job, 0, result, currentPos, job.length);
 currentPos += job.length;
 }
 return result;
 }
answered Nov 17, 2012 at 23:19
4
  • Thank you. Still a little confused though... Do I then call generalConcatAll 4 times and pass in each jobs array? Commented Nov 17, 2012 at 23:23
  • Or do I call it once and run the for loops 4 times once for each of the jobs arrays? Commented Nov 17, 2012 at 23:24
  • No. The body of concatAll method gives you the anwer - you pass each job array as a seperate argument. Commented Nov 17, 2012 at 23:24
  • @TríonaLounds You might want to read about Varargs. Commented Nov 17, 2012 at 23:25
4

This is a bit more concise, and handles all null cases correctly using Apache Commons Lang library. ArrayUtils.addAll(T[], T...)

public String[] generalConcatAll(String[]...arrays) {
 String[] result = null;
 for(String[] array : arrays) {
 result = ArrayUtils.addAll(result, array);
 }
 return result;
}
answered Mar 13, 2014 at 14:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.