[英]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). 将当前位于该位置的元素(如果有)和任何后续元素右移(增加其索引)。
goods.addAll(1, foods);
goods.remove("Foods");
will work. 将工作。
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#addAll(int,%20java.util.Collection) https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#addAll(int,%20java.util.Collection)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.