0

I have two array lists namesArrayList1 and namesArrayList2, each contains values.

my question is how to put the two Array Lists in one array allNames[]?

willeM_ Van Onsem
482k33 gold badges483 silver badges624 bronze badges
asked Jun 15, 2017 at 2:37
2
  • 1
    have you tried anything yet? Commented Jun 15, 2017 at 2:38
  • nope still searching for an answer Commented Jun 15, 2017 at 2:40

3 Answers 3

5

Create a new list from existing list 1

List<String> allList = new ArrayList<>(namesArrayList1)

Add all others

allList.addAll(namesArrayList2);

Convert to array

String[] allArray = allList.toArray(new String[]{}); 
answered Jun 15, 2017 at 2:42
Sign up to request clarification or add additional context in comments.

Comments

0

Simply use System.arraycopy():

String[] allNames = new String[namesArrayList1.size() + namesArrayList2.size()];
System.arraycopy(namesArrayList1.toArray(), 0, allNames, 0, namesArrayList1.size()); 
System.arraycopy(namesArrayList2.toArray(), 0, allNames, namesArrayList1.size(), namesArrayList2.size());

Example:

List<String> list1 = new ArrayList<>();
list1.add("aa");
list1.add("bb");
list1.add("cc");
list1.add("dd");
List<String> list2 = new ArrayList<>();
list2.add("ee");
list2.add("ff");
list2.add("gg");
list2.add("jj");
String[] allNames = new String[list1.size() + list1.size()];
System.arraycopy(list1.toArray(), 0, allNames, 0, list1.size()); 
System.arraycopy(list2.toArray(), 0, allNames, list1.size(), list2.size());
for (String all : allNames) {
 System.out.print(all+ " ");
}

Output:

aa bb cc dd ee ff gg jj 
answered Jun 15, 2017 at 2:40

Comments

-1

I found a one-line solution from the good old Apache Commons Lang library.

ArrayUtils.addAll(T[], T...)

Code:

String[] both = (String[])ArrayUtils.addAll(first, second);

or you can use this code

int[] array1and2 = new int[namesArrayList1.length + namesArrayList2.length];
System.arraycopy(namesArrayList1, 0, array1and2, 0, namesArrayList1.length);
System.arraycopy(namesArrayList2, 0, array1and2, namesArrayList1.length, namesArrayList2.length);

This will work regardless of the size of namesArrayList1 and namesArrayList2.

answered Jun 15, 2017 at 2:40

Comments

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.