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

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

问题描述

我有两个相同大小的 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"]

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

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