2

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

2
  • 2
    Clone the list? Commented Apr 20, 2018 at 11:25
  • It is same with clone. On the second execution of the app, when the object is added in the list1, list2 automatically add it too. Commented Apr 20, 2018 at 11:28

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.