I'm new to Java. I tried to store iterators of LinkedList elements in a Map, and delete them later:
Map<Integer, Iterator<Integer>> map = new HashMap<>();
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(1);
map.put(1, list.iterator());
list.addFirst(2);
map.put(2, list.iterator());
Iterator<Integer> iter = map.get(1);
iter.next();
iter.remove(); // list is supposed to be [2]
However, ConcurrentModificationException
occurs. I think as soon as I add '2' in the list, the iterator of '1' expires, right?
In C++, list<int>::iterator
represents the pointer of a node from a linked list, which stays constant and available whenever new nodes are inserted into the list. I'm a little bit confused about this in Java.
Sorry for the confusion. Now I know that Iterator
is usually used in iterations, not to 'locate' an element, which is a bit different from that in C++.
I actually try to preserve the reference of elements from a linked list, so that the elements can be efficiently accessible in a complexity of O(1) instead of O(n).
Is there any related kind of Collection or Util? Or maybe I have to implement DeLinkedList
and DeLinkedNode
by myself. Thanks in advance.