如何连接两个ArrayList? [英] How to concat two ArrayLists?

查看:49
本文介绍了如何连接两个ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相同大小的 ArrayList .列表 1 包含 10 个姓名,列表 2 包含他们的电话号码.

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

我想将姓名和数字合并为一个 ArrayList.我该怎么做?

I want to concat the names and number into one ArrayList. How do I do this?

推荐答案

您可以使用 .addAll() 将第二个列表的元素添加到第一个:

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

array1.addAll(array2);

根据您上面的说明(我想要一个包含名称和编号的新 Arraylist 中的单个字符串."),您可能想要循环通过第一个列表并将第二个列表中的项目附加到它.

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.

像这样:

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
}

如果你输入:

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

您将获得:

array3 : ["a 1", "b 2", "c 3"]

这篇关于如何连接两个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆