I have an arraylist with names, phone numbers and locations.
I would like to remove certain items from that array if possible
Is there anyway to remove the item once I have found it like I have tried below?
public void delete(String nameToDelete)
{
for (Entry entry : Directory.entries) {
if (entry.name.equalsIgnoreCase(nameToDelete))
{
//remove(entry);
}
}
}
Thanks
解决方案
Reason?
Iterators returned by ArrayList is fail-fast in nature.
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Where does this iterator Come from while I am not using it?
For enhanced for loop for collections Iterator gets used so you can not call remove method while you are iterating.
So your loop is same as below
for (Iterator i = c.iterator(); i.hasNext(); ){
What is the Solution Then ?
You can call iterator.remove(); and change loop based on iterator explicitly rather than implicitly.
String inputWord = "john";
ArrayList wordlist = new ArrayList();
wordlist.add("rambo");
wordlist.add("john");
for (ListIterator iterator = wordlist.listIterator(); iterator
.hasNext();) {
String z = iterator.next();
if (z.equals(inputWord)) {
iterator.remove();
}
}
System.out.println(wordlist.size());
Now Where Can I Read more?