user1494530
user1494530

Reputation: 415

Does the object variable create an instance of the object while using a for-each loop in Java?

I am using the following code to add a new StockRecord to my stockRecords collection. StockRecord extends Stock.

for (Stock s : stock) {
     stockRecords.add(new StockRecord(s.get_storeID(),
     s.get_sku(), s.get_itemCount()));
}

I have a println statement in the constructors of both Stock and StockRecord. When I run this code, I get the following output:

Stock()
StockRecord()
Stock()
StockRecord()
Stock()
StockRecord()
Stock()
StockRecord()

Does using the variable s in the for-each loop actually create an instance of Stock?

Upvotes: 0

Views: 72

Answers (4)

mdgeorge
mdgeorge

Reputation: 360

It does not. For loops use java iterators. In each iteration of the loop, Iterator.hasNext and Iterator.next are called on the object returned by stock.iterator(). The java.util collections will not create new objects, but if you have a custom collection it might.

The other possibility is that you are creating objects in your calls to the getters or in the body of the StockRecord constructor itself. Look for "new" in those places.

Upvotes: 3

Paul Bellora
Paul Bellora

Reputation: 55223

Whenever a new object is instantiated, its parent constructor is called before its own constructor (and so on up to Object). Since StockRecord extends Stock, when you call new StockRecord a certain Stock constructor is called before the specified StockRecord constructor. That's why you're seeing those print statements and in that order.

Upvotes: 2

Bruno
Bruno

Reputation: 122669

The instances of Stock you're referencing in s at each iteration already exist. You are however creating a new instance of StockRecord every time (which may in turn create other instances of other classes).

Upvotes: 1

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Stock s picks up reference from collection/array object stock. It will not create any object.

Upvotes: 0

Related Questions