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();
}
}
在此功能中,我正在将旧列表与新列表进行比较。
第一个while循环检查是添加的任何新用户,第二个while循环检查是删除的任何用户。
当我运行此应用程序时,我的第一个while循环仅执行,而第二个while循环则不执行。
我检查了Log.i(“ Test”,“ inside!”);我发现它不在我的第二个while循环内。
请帮忙
最佳答案
您需要重新初始化迭代器,
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();
}
}