I have a question. What is wrong with regards to the below code:
ArrayList tempList2 = new ArrayList();
tempList2 = getXYZ(tempList1, tempList2);
//method getXYZ
getXYZ(ArrayList tempList1, ArrayList tempList2) {
//does some logic and adds objects into tempList2
return tempList2;
}
The code will get executed but it seems by passing tempList2 to the getXYZ method argument, it is doing object recycling.
My question is, Is recycling the tempList2 arraylist object correct?
I don’t quite know what you mean by “recycling”. This doesn’t appear to be a case where the application is recycling objects in an attempt to avoid allocating new objects. (That is the normal meaning of “recycling” in Java.)
If
getXYZis called multiple times with the sametempList2object, then this is simply a way of aggregating stuff into a single list. The fact thatgetXYZreturns anArrayListleaves open the possibility that the method implementation may be changed to return a differentArrayListinstance. That’s not a problem per se, but it might be if the caller doesn’t assign the result of the call appropriately.If
getXYZis only called once for any giventempList2object, then this looks a bit strange.In summary, this code looks a bit fishy, and is fragile if someone changes the implementation of
getXYZ. However, it is not down-right wrong, and there may be some good reason (or historical reason) for doing things this way that is not apparent in the small chunks of code you included in the question.EDIT – in response to this comment (inlined to make it readable)
The real conventional way of doing this would be:
or
Neither of these require creating the unnecessary
ArrayListinstance of your approach, and neither require passing 2ArrayListinstances into thegetXYZmethod.