RealDEV
RealDEV

Reputation: 131

Java - ArrayList / Array

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[]?

Upvotes: 0

Views: 203

Answers (3)

Blasanka
Blasanka

Reputation: 22417

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 

Upvotes: 0

Java Devil
Java Devil

Reputation: 10959

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[]{}); 

Upvotes: 5

美丽美丽花
美丽美丽花

Reputation: 212

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.

Upvotes: -1

Related Questions