List mylist = new ArrayList();
ArrayList mylist2 = new ArrayList();
I am wondering wha
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.
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?
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.
For myList
, you will only be able to invoke methods of the List
interface.
For example, you cannot invoke the method ensureCapacity
on myList.
You can think of it as polymorphism.
List<Integer> mylist
declares it to be a List, but it doesn't have to be an ArrayList - JVM just knows that it implements the List interface.
ArrayList<Integer> mylist2
declares it to be an ArrayList, so JVM knows that not only is it a List, it's an ArrayList in particular.
I know that List is an interface that ArrayList class implements.
That's exactly the difference :)
When you're using the two variables (mylist) and (mylist2) in code, you would have access to any methods that ArrayList defines that aren't part of the basic List interface only on mylist2.