I want to delete/remove an object from an array list of objects. Would this work if my class was:
class bookings {
public String getuser () {
return user;
}
public Date getbooking() {
return bookingDate;
}
private String user;
开发者_StackOverflow社区 private Date bookingDate;
}
and I had an arraylist similar to:
ArrayList <bookings> book;
public void foo (String user, Date date) {
for (bookings b : book) {
if (user.equals(b.getuser()) && date.equals(g.getbooking()) book.remove(b);
}
}
Firstly, you can't use a foreach loop for (bookings b : book)
because it won't allow you to modify the collection (it will throw an exception).
This code should work:
public void foo (String user, Date date) {
for (Iterator<bookings> i = book.iterator(); i.hasNext();) {
bookings b = i.next(); // Oops - forgot this line!
if (user.equals(b.getuser()) && date.equals(b.getbooking())
i.remove(); // Corrected this too!
}
}
It wouldn't hurt to name things using standard naming conventions and capitalization either:
class Booking {
String getUser() ...
Date getDate() ...
}
ArrayList<Booking> bookings;
FHr, Your way will have problem.
java.util.ConcurrentModificationException
which means you are modifying your collection concurrently both in your loop and removal.
If you want to know the root cause why the error occurs.
You'd better look into this post
Why doesn’t java.util.Collection define next(), hasNext() directly?
So please use Iterator instead.
Iterator it = list.iterator();
while(it.hasNext()){
Object o = it.next();
//check your object here such as equals,
//the safe way is to use Iterator here.
it.remove();
}
You can refactor it with bookings type in your Iterator like Iterator<bookings>
Please check this: The Collection Interface
Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
精彩评论