0

Hi kind of a noobish question, but I have a function that creates an ArrayList like

ArrayList<ArrayList<Integer>> inversePrefList = new ArrayList<>();

I append to this list throughout the function and inversePrefList ends up getting passed to main. My question is, in main do I have to declare a new object again? like

ArrayList<ArrayList<Integer>> inverseDoctorPrefList = 
            new ArrayList<>(createInversePreferenceList(problem.getDoctorPreference()));

or since the object already was allocated with 'new' in the function, should my line in main look like

ArrayList<ArrayList<Integer>> inverseDoctorPrefList = 
        createInversePreferenceList(problem.getDoctorPreference());

thank you.

Kimbo
  • 84
  • 1
  • 3
  • The best way to do things often depends on other things - like is the list that's returned used by other methods (and perhaps changed). – Mr R Mar 19 '22 at 10:10

1 Answers1

0

I finally figured it out and both ways would work. The first way would end up creating a new arraylist which would be a copy of the one passed from the function. the second way would not allocate new space, but it would use the same arraylist created/passed from the function. Thus both ways would work, but I recommend the second for code clarity and readability.

Kimbo
  • 84
  • 1
  • 3
  • Yes, the constructor used in the first way is called a [copy constructor](https://stackoverflow.com/a/10083129/5959593). Not related but C also has this. You can verify that the first way creates a new `ArrayList` by doing `inverseDoctorPrefList1 == inverseDoctorPrefList2`, which should return `false`. And normally, no one uses the first method unless they have a reason to do so. – Minh Nghĩa Mar 21 '22 at 08:16