Reputation: 21
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
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
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