This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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
What is the difference and when should we use the new and when is it just a waste of memory? Thanks. CHAD
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 ]
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
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.
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.