用两个或多个其他元素替换列表中的单个元素,而不会影响其余元素的顺序 [英] Replace single element in list with two or more other elements without disturbing the order of the remaining elements
问题描述
是否有一种方法可以用两个或两个以上其他元素替换列表中的单个元素,而不会干扰列表的其余部分?我知道您可以将一个元素替换为另一个元素,但是我正在寻找要添加的多个元素.用例是我想根据特定条件将给定元素分为两个或更多元素.
Is there a way to replace a single element in a list with TWO or more other elements without disturbing the rest of the list ? I understand you can replace one element with another, but i'm looking for more than one element to be added. The use case is that I would like to split a given element into two or more elements based on a particular condition.
例如:假设列表包含图上从节点A到节点F的路径,如下所示:
A -> B -> C -> D -> E -> F
我想用其他两个元素替换节点C,例如节点X和节点Y.最终列表应如下所示:
A -> B -> X -> Y -> D -> E -> F
For example: Let's say the list contains the path from node A to node F on a Graph as follows: A -> B -> C -> D -> E -> F
I would like to replace node C with two other elements say node X and node Y. The final list should look as follows:
A -> B -> X -> Y -> D -> E -> F
注意:我仍在考虑实现过程,并且尚未最终确定使用任何特定类型的列表(ArrayList,LinkedList等).
Note: I am still thinking through the implementation and I have not finalized on using any particular type of list (ArrayList, LinkedList etc.) yet.
推荐答案
您可以使用myList.add({index},{object});将其添加到Java列表中. 因此,例如,如果您想在索引3处拆分某内容,则可以执行以下操作:
You can add to a Java list by using myList.add({index}, {object}); So if you want to split something at index 3 for example you could do:
myList.set(3, newObject1);
myList.add(3, newObject2);
因此,现在所有内容都移至左侧,而newObject1将位于索引4处.但是,请谨慎地在for循环中执行此操作,否则事情可能会变得混乱.
So now everything gets shifted to the left and newObject1 will be at index 4. Be careful about doing this in an for loop though, things can get messy.
这篇关于用两个或多个其他元素替换列表中的单个元素,而不会影响其余元素的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!