How to concat two ArrayLists?

后端 未结 7 1275
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 23:29

I have two ArrayLists of equal size. List 1 consists of 10 names and list 2 consists of their phone numbers.

I want to concat the names and number into

相关标签:
7条回答
  • 2020-12-14 00:16

    You can use .addAll() to add the elements of the second list to the first:

    array1.addAll(array2);
    

    Edit: Based on your clarification above ("i want a single String in the new Arraylist which has both name and number."), you would want to loop through the first list and append the item from the second list to it.

    Something like this:

    int length = array1.size();
    if (length != array2.size()) { // Too many names, or too many numbers
        // Fail
    }
    ArrayList<String> array3 = new ArrayList<String>(length); // Make a new list
    for (int i = 0; i < length; i++) { // Loop through every name/phone number combo
        array3.add(array1.get(i) + " " + array2.get(i)); // Concat the two, and add it
    }
    

    If you put in:

    array1 : ["a", "b", "c"]
    array2 : ["1", "2", "3"]
    

    You will get:

    array3 : ["a 1", "b 2", "c 3"]
    
    0 讨论(0)
提交回复
热议问题