Iterate through the list, removing three ways of specifying objects:
1, and then define a list to save the objects that need to be deleted:
To modify part of the code:
list<user> userremove = new arraylist<user> ();
Locate the user System.err.println to delete
("Users to Delete:");
for (User result:list)
{
if (result.getid () = 1 | | | Result.getid () = = 3)
{
userremove.add (result);
SYSTEM.ERR.PRINTLN ("ID:" + result.getid () + "\tname:" + result.getname ());
}
List.removeall (userremove);
The remaining user
System.err.println ("The rest of the user:");
for (User result:list)
{
System.err.println ("ID:" + result.getid () + "\tname:" + result.getname ());
}
2, do not For-each cycle, with the original writing method: This way if deleted by object can be written as follows, if you want to delete by index please flashback loop
for (int i = 0; i < list.size (); i++)
{
User result = List.get (i);
if (result.getid () = = 3)
{
list.remove (result);
SYSTEM.ERR.PRINTLN ("ID:" + result.getid () + "\tname:" + result.getname ());
}
3. Remove with iterator
Iterator<user> it = List.iterator ();
while (It.hasnext ())
{
User userobj = It.next ();
if (userobj.getid () = = 3)
{
it.remove ();
}
}
The remaining user
System.err.println ("The rest of the user:");
for (User result:list)
{
System.err.println ("ID:" + result.getid () + "\tname:" + result.getname ());
}
PS: for-each traversal is actually working with the iterator iterator
iterator:
Iterator is working in a separate thread and has a mutex lock, This means that iterator is not allowed to be changed by the object of the iteration when it is working. When iterator was created, a Memory index table (a single linked list) was established. This index table points to the original object, when the original number of objects change, the contents of this index table does not synchronize, so when the index pointer moved down, you can not find the object to iterate, and then generate an error. List, set, etc. are dynamic, variable number of data structure, but iterator is one-way immutable, can only read sequentially, can not reverse the operation of the data structure, when the iterator point to the original data changes, iterator lost his direction.
* Three ways to easily learn later. *