I have been reading code from many Android projects recently to gain more understanding. one of the things I see is the difference in two ways that ArrayList are instantiated.
Note these two examples shown here. why do some use example 1, and why would you do that over example 2, what are the major differences between them?
I understand the concept of upcasting and downcasting in Java and don't see any advantage in this particular situation. if you are going to create an arrayList why not store it in an ArrayList variable from the beginning?
I have always used the example 2 way of creating a new ArrayList. I don't understand what is the advantage to use what is shown in example 1
It looks like more programmers use the example 1 way
Example 1, use of upcasting into parent variable
List<String> list = new ArrayList<String>();
Example 2
ArrayList<String> list = new ArrayList<String>();
List
is an interface and so can't instantiate it..You have to instantiate with its concrete implementations like ArrayList
.
Whether to use List
or ArrayList
totally depends on the context where it is being used..
If you want an ArrayList
you should instantiate it with an ArrayList though
Upcasting is usually performed for the purpose of reusability of a method and is usually done automatically..
Consider this method for sorting a list
public void sort(ArrayList lst);
You can only sort an ArrayList through this method.So if you want to sort LinkedList object you would have to create another method with LinkedList parameter
Now consider this method
public void sort(List lst);
You could now reuse this method by passing objects of the classes that implement List interface..So, you can now sort ArrayList
,LinkedList
,Stack
,Vector
using this same method..Thus you are now reusing this same method to sort different classes that implement List interface