List<Integer> mylist = new ArrayList<Integer>();
ArrayList<Integer> mylist2 = new ArrayList<Integer>();
I am wondering what is the actual difference between the above two in java collections API. I am new to java collections API. I know that List is an interface that ArrayList class implements.
The List<Integer>
version is the interface type - it only allows you to perform the methods declared by the interface, while the ArrayList<Interger>
typed variable allows you to do anything that is declared in the ArrayList<Interger>
and its supers. (including the List
of course).
However, though it seems "useless" to chose the first - it actually allows you more flexibility - it will help you change your design much easier if you will later decide you want a LinkedList<Interger>
(for example) and not an ArrayList<Interger>
as the dynamic type.
Addition:
Of course it doesn't mean you need to automatically chose the List<Integer>
version. If you actually need to use the exact type of ArrayList
- you should chose it. A good rule of thumb is to start with the interface version, and change it to the ArrayList<Integer>
only if you find yourself straggling to get something you would have done very easily with an ArrayList
type (or if you find yourself casting to an ArrayList
...)
In your statement 1, since you are referring mylist
as List<Integer>
while it is still ArrayList<Integer>
, hence you can use the methods available in the List
interface ONLY. This is better statement, if you are using cross class.method functionality.
Also any method accepting List<Integer>
can accept any of the implementation classes of List
e.g. LinkedList<Integer>
or your custom implementation class.
Your second statement, creates and references the object as ArrayList<Integer>
ONLY. Some people perefer it when mylist
is to be used locally in the method.
Always code to the interface.
(Car analogy alert)
You walk into Hertz Rent-a-Car. You say, I want an IVehicle
. They say, "well, what kind of IVehicle
?" You don't care. So they give you a DumpTruck
. But you don't want a dump truck, you want something compact. You want an ICompact
that extends IVehicle
. So they give you a motorcycle. "No!" you exclaim, "I want an ICar
!" "What kind of ICar
?" they ask. "I don't care!" you exclaim. So they give you a FordCar
, and you live happily ever after.
Does that clear it up?
First one is called coding to interfaces.
Using the List
reference through out your code you can update the concrete implementation to something else like a LinkedList
without breaking your client code.
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