I have seen some examples of usage and some use the ArrayList statement, List<>
and ArrayList<>
at startup.
I have seen some examples of usage and some use the ArrayList statement, List<>
and ArrayList<>
at startup.
The two statements below have the same effect.
List<String> lista = new ArrayList<String>();
ArrayList<String> lista2 = new ArrayList<String>();
The only difference is that the variable lista
may receive other implementations of List
. For example:
lista = new LinkedList<String>();
Since you have defined the type of variable List<String>
, this is completely possible. If it were with the variable lista2
, this would not be possible.
I will not go into detail on this because there are many answers here on the site that talk about (linkei some of them below), but the difference between the two is that List
is the interface, ArrayList
is the implementation - the class implements the interface.
Interfaces can not be instantiated, they are only used to define a contract in the classes that implement it.
So you can not do
List<String> lista = new List<String>(); // É impossível instanciar uma interface
However, it is quite possible to do
List<String> lista = new ArrayList<String>();
You can always use the interface on the left side of the statement, this is a very common thing in object-oriented languages.
Eg:
List<String> lista = new ArrayList<String>();
List<String> lista2 = new LinkedList<String>();
/* Tanto ArrayList, quanto LinkedList implementam List. Por isso a declaração
pode ser feita desta forma */
You can learn more about interfaces in the questions below
Is an interface a variable?
In object orientation, why are interfaces useful? Abstract Class X Interface
In OOP, can an interface have attributes?
< When should I use Inheritance, Abstract Class, Interface, or a Trait?