Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

the 'new' initialization

 
chad stevens
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I am a little confused about this basic question. Sometimes I see List theList = new ArrayList(); and sometimes I see List theList and then the list is getting values from somewhere without the new.. example

compared to:

What is the difference and when should we use the new and when is it just a waste of memory? Thanks.
CHAD
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference and when should we use the new and when is it just a waste of memory? Thanks.

The difference is that when you use new you create a, well, new unique instance of some class, whereas in the other case the method returns an already existing instance. When is it a waste of memory to create new instances? That's really a very subjective question which depends on a lot of factors. Should you create an array filled with a hundred or more List objects? Probably not. But in general if you have a use for a new instance in your program then you should not be concerned about creating it. Some objects like threads or database connections which use a lot of system resources, you should certainly think twice about. That's why you will see terms like "thread pooling" in which you create a finite number of threads and use whichever one is inactive upon a client request.
[ May 23, 2003: Message edited by: Michael Morris ]
 
Gary McGath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the examples you posted, the second one would be a clear waste of memory. You would be creating an instance of List and then immediately overwriting it with the value returned from getVals(). The first List would eventually have to be garbage collected, consuming processing resources.
 
chad stevens
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Gary,
That's pretty clear now, I suppose that you would only create a new instance when you will create and put new elements in, although, going through other people's code it seems to be quite common to see those 'wasted' assignments.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic