Replace single element in list with two or more other elements without disturbing the order of the remaining elements

java, list

Solution

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);

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.

Problem

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. 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` Note: I am still thinking through the implementation and I have not finalized on using any particular type of list (ArrayList, LinkedList etc.) yet.

Original source

Related problems