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
RealDEV
1311 gold badge2 silver badges9 bronze badges
-
1have you tried anything yet?Scary Wombat– Scary Wombat2017年06月15日 02:38:42 +00:00Commented Jun 15, 2017 at 2:38
-
nope still searching for an answerRealDEV– RealDEV2017年06月15日 02:40:20 +00:00Commented Jun 15, 2017 at 2:40
3 Answers 3
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
Java Devil
11.1k7 gold badges37 silver badges50 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Blasanka
22.6k12 gold badges107 silver badges109 bronze badges
Comments
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
美丽美丽花
2121 gold badge4 silver badges16 bronze badges
Comments
lang-java