public void compare(ArrayList list_old, ArrayList list_new) {
try {
Iterator<User> iterator_old = list_old.iterator();
Iterator<User> iterator_new = list_new.iterator();
//Check New User Is Added
while (iterator_new.hasNext()) {
Log.i("Test", "inside!");
User user_new = iterator_new.next();
boolean NEW = true;
while (iterator_old.hasNext() && NEW) {
User user_old = iterator_old.next();
if (user_new.getUsername().equals(user_old.getUsername())) {
NEW = false;
}
}
if (NEW) {
generateNotification(getApplicationContext(), user_new.getUsername() + " has been added.");
}
}
//Check User Is Removed
while (iterator_old.hasNext()) {
Log.i("Test", "inside");
User user_old = iterator_old.next();
boolean NEW = true;
while (iterator_new.hasNext() && NEW) {
User user_new = iterator_new.next();
if (user_old.getUsername().equals(user_new.getUsername())) {
NEW = false;
}
}
if (NEW) {
generateNotification(getApplicationContext(), user_old.getUsername() + " has been removed.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
请帮忙
答案 0 :(得分:2)
您需要重新初始化迭代器,
public void compare(ArrayList list_old, ArrayList list_new) {
try {
Iterator<User> iterator_old;
Iterator<User> iterator_new = list_new.iterator();
//Check New User Is Added
while (iterator_new.hasNext()) {
Log.i("Test", "inside!");
User user_new = iterator_new.next();
boolean NEW = true;
iterator_old = list_old.iterator();
while (iterator_old.hasNext() && NEW) {
User user_old = iterator_old.next();
if (user_new.getUsername().equals(user_old.getUsername())) {
NEW = false;
}
}
if (NEW) {
generateNotification(getApplicationContext(), user_new.getUsername() + " has been added.");
}
}
//initialize again
iterator_old = list_old.iterator();
//Check User Is Removed
while (iterator_old.hasNext()) {
Log.i("Test", "inside");
User user_old = iterator_old.next();
boolean NEW = true;
iterator_new = list_new.iterator();
while (iterator_new.hasNext() && NEW) {
User user_new = iterator_new.next();
if (user_old.getUsername().equals(user_new.getUsername())) {
NEW = false;
}
}
if (NEW) {
generateNotification(getApplicationContext(), user_old.getUsername() + " has been removed.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
您并未在任何地方重置迭代器,因此我认为任何代码都无法正常工作。如果你使用for-each循环,你的代码可能会工作并且更具可读性,所有Iterable类都支持。这将避免完全创建和重置迭代器的需要。
for (User newUser : list_new) {
for (User oldUser : list_old)
// Compare
}
for (User oldUser : list_old) {
for (User newUser : list_new)
// Compare
}