[英]Java - Add an element between two elements in arraylist
i want to add an element between two other elements in an arraylist like:我想在 arraylist 中的其他两个元素之间添加一个元素,例如:
Element 1
Element 2
Element 3
Adding an element:添加元素:
Element 1
Element 4 <---- Adding element 4 between 1 and 2.
Element 2
Element 3
Is this possible?这可能吗?
Yes - you want the overload of add
that takes an index .是的-您希望
add
采用 index 的重载。 In this case, the index would be 1:在这种情况下,索引将为 1:
list.add(1, 4); // Index then value
Note that adding an element involves copying all existing elements after that (so values 2 and 3 in your example), so if you do this a lot with a very large list, it can have performance implications.请注意,添加元素涉及复制所有现有元素(因此示例中的值为 2 和 3),因此如果您对非常大的列表执行此操作,可能会对性能产生影响。
Yes, you can use the add() method of ArrayList to insert an element at any particular index.是的,您可以使用 ArrayList 的 add() 方法在任何特定索引处插入元素。
Assuming the name of your ArrayList is list, you can add 4 at index 1 in this manner-假设您的 ArrayList 的名称是列表,您可以以这种方式在索引 1 处添加 4 -
list.add(1, 4);
The first parameter takes the index and the second parameter takes the value of the element you want to insert.第一个参数采用索引,第二个参数采用您要插入的元素的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.