actually it is not about performance. it is more about the flexibility and reduced coupling.
by using the first code you can assign the reference to objects of other types implementing List interface.
also using interfaces and its methods leads to lower coupling which is of course a good practice.
SCJP 5.0 SCWCD 5.0
Joined: Oct 14, 2002
I agree with Avi,
To take it a little further, I would go so far as to say that 99% of the time performance should be about the last thing you consider when you're writing code. Oh I know it 's occasionally important, but most of the time what's most important in your code is:
Eliminate fossil fuel subsidies. (If you're not on the edge, you're taking up too much room.)
Joined: Nov 24, 2009
Rahul Shivsharan wrote:but whats the benifit of the first code snippet over the second?
Any potential benefits depend on the situation.
As a general principle you should write code using variables of the most abstract type that fits the situation. The higher up the inheritance chain, the more abstract is the type. In your example List is more abstract that ArrayList. If you write code using List variables the code will be more flexible than if you wrote it using ArrayList variables. The reason is that your code will work not only with ArrayList objects but with any object implementing the List interface (like say LinkedList). So the rationale behind the general principle is that the more abstract the types you use in code, the more object types will it potentially work with, and the more flexible your code will be.
BUT, there's often a limit to how high an abstraction can be for it to "fit the situation". Say for example you're coding an algoritm using List variables and you make extensive use of the random accesses List permits. Then everything will work fine as long as ArrayList objects are used. But when the day comes that someone decides to plug in LinkedList objects in your code instead, it will be a performance disaster. So in this particular example, List was too abstract. It didn't fit the situation. You really should've used the more specific ArrayList type.
So when you apply the general principle (and aim for a high abstraction level in order to write flexible code) you need to think twice. Am I maybe inviting disaster by being too abstract here? Or maybe not abstract enought? In your example maybe this is a better choise,