I wasn't sure how to search for an answer to this.
What is the difference between the following declarations?
List<Integer> al = new ArrayList<Integer>();
ArrayList<Integer> al = new ArrayList<Integer>();
I sometimes see the first declaration being used but as ArrayList inherits methods from it's superinterfaces and superclasses, I'm not sure why that is used. Would someone be able to clarify? Thanks!
You should not be dependent on implementation of interface. If you use List<Integer> al = new ArrayList<Integer>(); - you'll be able to change implementation easily, without affecting all other code, because you're using only methods, defined in List interface.
Using ArrayList<Integer> al = new ArrayList<Integer>();, you become bound to one implementation of interface, and your class becomes coupled much more tightly to implementation, which usually must be avoided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With