Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Collections in Java

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!

like image 364
201403540 Avatar asked Dec 01 '25 21:12

201403540


1 Answers

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.

like image 194
Rayan Ral Avatar answered Dec 04 '25 11:12

Rayan Ral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!