简体   繁体   English

将一个列表插入到另一个列表中

[英]Insert one list into another list in position

For instance, there are two lists 例如,有两个列表

List<String> goods = new ArrayList<String>();
goods.add("Vegetables");
goods.add("Foods");
goods.add("Drinks");

List<String> foods = new ArrayList<String>();
foods.add("Beef");
foods.add("Chicken");

What is the best way to insert foods into goods into position of Foods ie into 1 position replacing the Food with the content of foods ? 什么是插入食物转变成商品进入的位置,最好的办法Foods即到1个位置替代Food与内容foods

So that goods will contain: 这样goods将包含:

Vegetables, Beef, Chicken, Drinks 蔬菜,牛肉,鸡肉,饮料

You can use List.addAll() , but you also have to remove the Foods entry after doing the insertion. 您可以使用List.addAll() ,但在插入后必须删除Foods条目。

goods.remove("Foods");  // remove by object (String name)
goods.addAll(1, foods);

From the documentation for List.addAll(int index, Collection c) : List.addAll(int index, Collection c)文档中:

Inserts all of the elements in the specified collection into this list, starting at the specified position. 从指定位置开始,将指定集合中的所有元素插入此列表。 Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). 将当前位于该位置的元素(如果有)和任何后续元素右移(增加其索引)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM