What is the difference, advantages, disadvantages between:
List a=new ArrayList();\\suponiendo que introducire numeros enteros
ArrayList a=new ArrayList(); \\suponiendo que introducire numeros enteros
ArrayList<Integer> a=new ArrayList<Integer>();
List <Integer> a=new ArrayList<Integer>();
Or are they all equivalent?
Note: instead of ArrayList
could also have been LinkedList
or someone else.
The difference lies in what each thing is:
List
is an interface (which extends interfaceCollection
)ArrayList
is a class (which implements the interfaceList
)Although all the options you specify will work correctly, using the interface
List
has advantages over using the implemented classArrayList
because you might benefit from polymorphism in object-oriented programming.For example, if later in your project you see that you need to change the implementation, if you've defined your variable as
List
you shouldn't have much of a problem changing fromArrayList
to another type of class that implements the interfaceList
(LinkedList
for example). That is why options 1 and 4 may be more advantageous.And now, to define the type parameter of the list (options 3 and 4) or not to define it (options 1 and 2)... it's going to depend on what you want to do. If you define it, then the types will be validated at compile time, which can help you find errors, but will give you less flexibility later.
As it seems that you are clear about what you are going to use
Integer
and not others, then perhaps it is better for you to define the type (option 4), because it will make the code easier to maintain and debug.In principle they are all equivalent, that is, the difference between one and the other does not affect you when compiling. But internally there is a difference and it is that at run time, the list will be instantiated as Object.
Anyway, I recommend you to instantiate it as ArrayList, so everything is clearer.
Greetings.