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 );
  }
5
  • 3
    Is partitionsCopy a deep copy? Commented May 1, 2013 at 13:09
  • stackoverflow.com/questions/993025/… Commented May 1, 2013 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? Commented May 1, 2013 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. Commented May 1, 2013 at 13:31
  • Are any other threads modifying the outer or inner lists? Commented May 1, 2013 at 13:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.