xmlParser
xmlParser

Reputation: 2021

Object from one ArrayList saved in another ArrayList before executing the copy block

I have app with scheduler. It runs the app every 30 sec.

In my app I have list1 and list2

  static List<Post> list1 = Collections.synchronizedList(new ArrayList<Post>());
  static List<Post> list2 = Collections.synchronizedList(new ArrayList<Post>());

for (int i = 0; i < responseGetAllNew.size(); i++) {
      Object1 obj1 = new Obj1();
       obj1.setName("JOHN");

      if (list1.contains(pt)) {
        System.out.println("Already in the list");
      } else {
        list1 .add(obj1 );
      }
 }

 private List<Object1> getNewAndChanged() {
    List<Object1> newObjs = new ArrayList<Object1>();
    for (Object1 obj1 : list1) {
      if (!list2.contains(obj1 )) {
        newObjs.add(obj1 );
      }
    }
    return newObjs;
  }

and after this:

list2 = list1;

So my problem is when I add new object to list1 through soapUI and when the program comes to list1.add(obj1); It adds the object in list1 but somehow it adds the object in list2 too.

So my question is what can cause this and how to avoid the object to be written in list2 before this line to be executed list2=list1

Upvotes: 2

Views: 52

Answers (1)

Shubhendu Pramanik
Shubhendu Pramanik

Reputation: 2751

It is because both the objects are referring to the same instance. You need to clone it or create the second object like below:

list2 = new ArrayList<>(list1);

Upvotes: 2

Related Questions