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.
By using the name of the interface List, you give more flexibility. You can change the ArrayList implementation to another implementation (eg Vector, LinkedList) secure in the knowledge that it will make no difference to the correctness of your code.
This is called "program to the interface, not the implementation."
Other people will doubtless wish to give you more details.
Campbell's explanation of why we use List is correct, but I think you were asking a different question.
I read the question as why do we do this:
Instead of this:
If I am reading your question correctly, then I believe the answer is style.
Joined: Oct 13, 2005
If I've answered the wrong question, sorry. I would prefer to see such a field (not a local variable) instantiated in the constructor, both to prevent null problems, and to ensure it is always the same instance used.
Joined: Oct 01, 2008
Sorry, I did not get it. Can you explain more in detail.
I repat my question ... Why we do not write in this way...
but prefer to write
Joined: Oct 13, 2005
Creating a new ArrayList inside the doProcess() method is probably a bad idea; you will lose any information which has been added previously.
The first declaration
is better; it ensures that the List is always created when the class is instantiated, and reduces the risk of having it null. I would prefer (mainly for stylistic grounds; it probably has no performance effect) to see the field initialised in a constructorEven better, if you are sure you want the List to be the same List throughout the life of the object, would be to flag it "final" then you can be sure it won't become null, nor will you lose any information by mistake.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com