1

I need to create a list of clients, each of them having a list of jobs. when assigning a List to a client, it is passed by reference and any change made to the list ( clearing it for example ) is also reflected in the client object.

Client client = new Client();
Job job = new Job();
List<Job> jobs = new ArrayList<>();
client.job_run_user_login = "razvan";
job.action = "EMAIL";
jobs.add(job);
client.jobs = jobs;
jobs.clear();

client object before running " jobs.clear(); " line :enter image description here

client object before running " jobs.clear(); " line :enter image description here

How can I avoid this?

Razvan Olariu
  • 59
  • 1
  • 8
  • Are you saying you want two separate lists? One for the client, and one that you'll modify? – Dawood ibn Kareem Aug 01 '19 at 20:01
  • `client.jobs = jobs;` makes `client.jobs` and `jobs` the same list. That doesn't make a copy. You need to copy the list of you want them to behave independently. – Carcigenicate Aug 01 '19 at 20:02
  • 1
    Why do you need to clear the list anyway? Create a new list every time you create a client, and then just leave it alone. – Andy Turner Aug 01 '19 at 20:33
  • @AndyTurner I presented a simplified problem, my scope required me to reuse the list. – Razvan Olariu Aug 02 '19 at 13:08
  • @RazvanOlariu if the accepted answer works for you, I don't see why you need to reuse the list, or even have the list in the first place. You could alternatively do `client.jobs = new ArrayList<>();`, and then do `client.jobs.add(job);`. – Andy Turner Aug 02 '19 at 13:11

1 Answers1

1

By copying a collection.

client.jobs = new ArrayList<>(jobs);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142