1

I'm trying to add an item to a list of lists. partitions is a LinkedList of lists of Strings. I'm trying to add an item to the begining of one of the partitions in the list of partitions, but I'm getting a ConcurrentModificationException, even though I'm using a copy of the list called partitionsCopy.

Is there any way to do this? All I can find are examples on how to remove items or add items using ListIterator, but I can't add an item at a specific position with ListIterator

int index = 0;
for (List<String<?>> partition : partitions) {
    if (index > 0) {
        partitionsCopy.get( index ).add(0, lastPartition.get(lastPartition.size() - 1));
    }
    lastPartition = partition;
    index++;
}

partitionsCopy looks like this

List<List<String<?>>> partitionsCopy = new LinkedList<List<String<?>>>( );
partitionsCopy.addAll( partitions );

Here's what I came up with from jtahlborn's answer.

  for ( List<String<?>> partition : partitions ) {
    List<String<?>> list = new ArrayList<String<?>>( );
    list.addAll( partition );
    partitionsCopy.add( list );
  }
labatyo
  • 486
  • 8
  • 17
  • 3
    Is partitionsCopy a deep copy? – Matt Stephenson May 01 '13 at 13:09
  • http://stackoverflow.com/questions/993025/java-adding-elements-to-a-collection-during-iteration – Subodh Joshi May 01 '13 at 13:10
  • Is `partitionsCopy` really a copy of the `List`, rather than just another reference to the same `List`? Where do you initialize that variable? – Rob I May 01 '13 at 13:10
  • Why does string have a generic argument on it in your code? Is it not a normal java.lang.String? Also, how is `lastPartition` declared? Looks to me like it's probably a reference to the same list as `partitions`, which would cause the issue. – Michael Berry May 01 '13 at 13:31
  • Are any other threads modifying the outer or inner lists? – Andy Thomas May 01 '13 at 13:43

1 Answers1

1

Your problem isn't with partitionsCopy, it's with whatever is in partitionsCopy (the nested List), as that is the List that you are actually modifying. When you copy partitions into partitionsCopy, you are only copying the references to the nested Lists. You are not copying the nested Lists themselves.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118