سؤال

I am trying to iterate (or use a for each loop) on a Linked list class and be able to change the item (when found) to a passed in parameter.

for(Item n : items) 
{
    if (n.getKey().equals(key))
    {
         n = new Item(key, value);
    }
}

Does this change of data work or is it temporary (only to be lost when the activation record is deleted)?

هل كانت مفيدة؟

المحلول

You can't iterate over a collection and modify it. You will always get a java.util.ConcurrentModificationException. First off all you need to use an iterator, to remove the item. Then you can use a second list to store the data you want to add.

Here you are an example:

LinkedList<String> linkedList = new LinkedList<String>();

        linkedList.add("This");
        linkedList.add("is");
        linkedList.add("an");
        linkedList.add("test");

        LinkedList<String> temp = new LinkedList<String>();

        for (Iterator<String> iterator = linkedList.iterator(); iterator.hasNext();) {
            String string = (String) iterator.next();

            if(string.equals("an")) {
                iterator.remove();

                temp.add("a");
            }
        }

        linkedList.addAll(temp);

You can call iterator.remove() to savely remove the current item from list.

نصائح أخرى

You are using fast enumeration, which protects the list that you are iterating through. If you would like to change the data in the list, you would need to use a traditional for loop.

Basically how fast enumeration works is it makes the array read-only in the block of code because you have no access to what integer the iteration is.

You could do this:

for(int i = 0; i < items.length; i++)
{
    if (n.getKey().equals(key))
    {
         items[i] = new Item(key, value);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top