Different Kinds of passing objects to Arrays

73 Views Asked by At

Is there a difference between creating an object and then passing it to ArrayList Or directly creating an object in ArrayList.add method? In case of memory use and performance? Example:

ArrayList<ClassX> arrayList = new ArrayList();
//Type 1:
ClassX object = new ClassX();
arrayList.add(object);
//Type 2:
arrayList.add(new ClassX());
2

There are 2 best solutions below

0
On BEST ANSWER

Logically? No - Both serve the same purpose.

Space? Yes. In type1: A reference will get created in stack hence extra memory allocation. And the object can now be accessed by either the reference variable or array list index.

0
On

Basically there are no differences between the 2 lines but the second one reduces a unnecessary variable creation. In the first one you can modify the first object since you have the reference to it.