Suppose there are two lists:

List<TestObject> testObject1 = new ArrayList<>(); List<TestObject> testObject2 = new ArrayList<>(); 

Internal objects can be repeated.

Can I make sure that these duplicate objects are not duplicated in memory?

That is, occupied one memory area instead of two?

  • it depends how you add them there - Saidolim

1 answer 1

 List<TestObject> testObject1 = new ArrayList<>(); List<TestObject> testObject2 = new ArrayList<>(); 

If done

 TestObject testObject = new TestObject(); testObject1.add(testObject); testObject2.add(testObject); 

then one object will be in 2 lists

  • and if the objects are valid, they are read from the database (new ones are created every time), and I don’t know in advance whether they will be the same. In this case, is it possible to avoid repetition in memory? - iamtihonov
  • if from the database you are sure that they are the same for every request (usually not) then you can find the item from the first list by ID and transfer it to the 2nd list - Saidolim
  • Every time you add a new object to the second list, check if the object exists in the first one, will it be a good solution? Maybe it's better to duplicate objects? - iamtihonov
  • @iamtihonov better duplicate objects, or create a 2nd list from the first. Every time checking it is certainly bad. But the author wants this - Saidolim