dcsimg
When to use Collection, ArrayList, Vector...
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Thursday, June 19, 2003 12:52 AM

In Java, when should I use Collection, ArrayList.


Example I have a function getData() that return some objects. Should I use


  Collection getData() {...}


or

  ArrayList getData() {...}


please help me!

Re: When to use Collection, ArrayList, Vector...

Posted By:   Stephen_McConnell  
Posted On:   Thursday, June 19, 2003 05:16 AM

You are asking a good question.


Collection is the top level interface that ArrayList implements.


Inside your method, you are probably using a concrete class of ArrayList to build the data. Look at the methods described in the Collection JavaDocs and if those will do, then make the signature of your method Collection.


This is because inside the class you may someday, for some reason or another want to change the concrete class!!! If you do that, then you have to change ALL the code that references your getData() method. And the consequences of doing that may be problematic, requiring more changes.


However, if you code to the interface then if you change the underlying implementation, you won't have to change ANY code.


Best practice is to try to always code to the interface. (Note the word try. It is the ideal rather than a hard and fast rule).


In your JavaDocs for the getData() method, you might want to state that (if you use ArrayList) the method is not thread safe (since ArrayList is a synchronized class). That way any developer using your method knows that is a side-effect of using your method.


Hope this helps


Stephen McConnell

About | Sitemap | Contact