Bytheway
Bytheway

Reputation: 21

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

Upvotes: 0

Views: 62

Answers (2)

Belwal
Belwal

Reputation: 473

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.

Upvotes: 0

Sujay Mohan
Sujay Mohan

Reputation: 952

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.

Upvotes: 0

Related Questions