Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object creation

 
kannan vinayagam Duraiswamy
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

code 1


code 2



what is the difference between these two codes
in code 2 : is the new arraylist object is created very time the loops run?.
in code 1 : only one arrauylist is created?.

 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Is the new arraylist object is created very time the loops run?.


Yes for both code 1 and 2
 
Kumari Priyanka
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In first case only one ArrayList object will be created in the heap.... while in second case 10 new ArrayList object will get created.....
 
Sridhar Santhanakrishnan
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In first case only one ArrayList object will be created in the heap.... while in second case 10 new ArrayList object will get created.....



Do you mean reference handlers? Anyways, both coding styles shouldnt matter as the gc will take care of the short-lived references.
 
Kumari Priyanka
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes.....gc will take care of the short lived references.....but the first is the best practice that you should follow......
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kumari Priyanka wrote:yes.....gc will take care of the short lived references.....but the first is the best practice that you should follow......


I disagree. If a variable is meant to be limited to a certain scope it shouldn't be declared outside of that scope, because it may then inadvertently escape its inteded scope.
If you minimize the scope of the variable this cannot happen and the variable will be more readily recognizable as a local variable to programmers that will have to maintain the code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic