3

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.

Shetty
  • 441
  • 5
  • 19
  • What do you mean by _"without disturbing the rest of the list"_? – Alexis C. Dec 02 '14 at 15:12
  • Yes you can insert elements but that will move all elements after the inserted element back one... – brso05 Dec 02 '14 at 15:13
  • What list implementation is this? (It makes a huge difference.) For something like ArrayList, you'd just replace one and insert another one before or after it. – Jon Skeet Dec 02 '14 at 15:13
  • 1
    if the list is sorted, i would like to maintain the sorted order. – Shetty Dec 02 '14 at 15:13
  • When you replace the element with element(s) will they be in the correct spot or will the list need to be re-sorted? – brso05 Dec 02 '14 at 15:15
  • 1
    Maybe you want a sorted set check out this link: http://stackoverflow.com/questions/8725387/why-there-is-no-sortedlist-in-java – brso05 Dec 02 '14 at 15:17
  • @brso05 The new elements will maintain the sorted order – Shetty Dec 02 '14 at 15:20
  • @JonSkeet Let's assume we're using an ArrayList for now. Does the solution change if i'm using any other implementation (say, a LinkedList etc.) ? – Shetty Dec 02 '14 at 15:21
  • @Shetty: Well for one thing, insertion into a linked list doesn't require copying. (Although IIRC, the Java API doesn't make it easy to do this as efficiently as we might like.) And if it's a sorted list, insertion at a point makes no sense. For another, an array-backed list (Arrays.asList) wouldn't allow insertion at all. – Jon Skeet Dec 02 '14 at 15:23
  • @Shetty If you are using ArrayList look at Bogdan Balas answer... – brso05 Dec 02 '14 at 15:25
  • @ZouZou, JonSkeet, brso05: I've added an example to the question. Please take a look and see if that helps clarify my question. – Shetty Dec 02 '14 at 15:39

1 Answers1

5

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.

brso05
  • 13,142
  • 2
  • 21
  • 40
Bogdan Balas
  • 355
  • 1
  • 6