javaobjectarraylistanonymous-objects

Different Kinds of passing objects to Arrays


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());

Solution

  • 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.