Faisal Shaikh Faisal Shaikh - 11 days ago 6
Java Question

Can anyone tell me why my old list has all the values which should be there only in the new list.?


  1. I am storing a list in tmp and then adding new values in list.

  2. On refresh I am comparing old list with new list.

  3. And if new list has new entry then generating notification but every time i find all the values in my old list.

    public void populateList(String result) {
    ArrayList<User> tmp;
    tmp = list;
    list.clear();
    try {
    JSONArray jsonArray = new JSONArray(result);
    for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject json_data = jsonArray.getJSONObject(i);
    String NAME = json_data.getString(StaticMember.NAME);
    String STATUS = json_data.getString(StaticMember.STATUS);
    list.add(new User(NAME, STATUS));
    }
    ArrayList tmpN = list;
    compare(tmp, tmpN);
    CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, list);
    lv.setAdapter((customAdapter));

    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public void compare(ArrayList list_old, ArrayList list_new) {
    try {
    Iterator<User> iterator_old = list_old.iterator();
    Iterator<User> iterator_new = list_new.iterator();

    while (iterator_new.hasNext()) {
    User user_new = iterator_new.next();
    boolean NEW = true;

    while (iterator_old.hasNext()) {
    User user_old = iterator_old.next();
    //Log.i(":N:"+user_new.getUsername(), ":O:"+user_old.getUsername());
    if (user_new.getUsername().equals(user_old.getUsername())) {
    NEW = false;
    break;
    }
    }
    if (NEW) {
    generateNotification(getApplicationContext(), user_new.getUsername() + " has been added.");
    Log.i("True", "Changed");
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }


Answer

When you do tmp = list you do not store the values of list in tmp. Instead, you simply make tmp reference the same object that list references. Later, when you modify list, you modify the content that tmp references.

Initially, list references the user list:

 list -> [user0, user1, user2]

After tmp = list, both list and tmp reference the same list:

 list -> [user0, user1, user2] <- tmp

When you call list.clear(), you clear the original list:

 list -> [] <- tmp

And when you add new elements to list, you modify the original list:

 list -> [newuser0] <- tmp

If you need to store a copy of list in tmp you need to create a new list before you modify the old one:

List<User> tmp = new ArrayList<>(list);

Note that the User objects stored in both lists are still the same though, so if you modify an object from one list, it will be reflected on the other.

Comments