Java use of subList()
I having problems with ConcurrentModificatio开发者_如何转开发nException
when I use a subList.
My question is: Is safe create a new collection using a subList?
Example:
List<T> list = new LinkedList<T>(someList.subList(0,n));
The result list must to be a independent list of the original list.
Sorry for my english.
If you need the sublist to be modifiable, this is about the easiest way to do it.
Without seeing more code, I'm assuming that another thread is probably modifying the contents of someList
, in which case you'll need to implement some sort of synchronization policy, such as a synchronized block when you attempt to extract a sub-list from it -- that's me shooting in the dark.
synchronized(someList){
// get sublist
}
EDIT
If you're attempting to remove an element from the sub-list in the middle of iterating over it, I'd recommend doing so using iterator.remove() since
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics
What you are doing to the create the list is safe in creating an independent List, in a single threaded environment.
Since you haven't specifically said so, I am assuming that the exception is occurring while that line of code is being executed. This means that you have another thread modifying the list while the new LinkedList is being created.
Depending on what the source List is, you may have other problems as well, unless it is a synchronized list of some sort. If it isn't, its behaviour could be very unpredictable.
If my assumption about the exception being in that line is incorrect, then please post the code where the exception is occurring since it is pretty easy to find if it is being done in a single thread.
精彩评论