user3755880
user3755880

Reputation: 375

Java: array of objects, two different approaches of initialization

I'm currently experimenting with initializing an array of objects, and came across the following two approaches of filling the array of objects:

Approach 1

Cat[] catArray = new Cat[num]
 
for (int i = 0; i < num; i++) {
    Cat someCat = new Cat();
    catArray[i] = someCat;
}

Approach 2

Cat[] catArray = new Cat[num]
 
for (int i = 0; i < num; i++) {
    catArray[i] = new Cat();
}

Is there any tangible difference in the above two ways of initializing and filling an array of objects in terms of memory usage and/or performance?

Upvotes: 0

Views: 51

Answers (1)

lolloz98
lolloz98

Reputation: 109

Objects in Java are always allocated in the heap, whereas their addresses is in the stack.

Thus, using approach 1 or approach 2 does not really make a difference: in approach 1 you are just copying num times more an address. This should not give you any performance issue.

The compiler might even optimize your code and run approach 1and approach 2 equivalently.

From a programming point of view, approach 1 does not really make sense: someCat is never used and it is not accessible after the for loop. In the for loop you can access the new Cat by simply using catArray[i].

Upvotes: 1

Related Questions