Statement from the Arraylist?

Asked

Viewed 804 times

-4

I have seen some examples of use and some use different Arraylist statement, List<> and ArrayList<> at first.

  • 3

    Arraylist is the implementation itself, which implements the List interface. So you can start this way: List<type> list = new ArrayList<>();

  • Complete the question please.

  • 2

    See this question An interface is a variable?. By the way, should we mark as duplicate? Since this responds to his...

  • @jbueno truth, the answer there explains exactly the doubt.

  • I wonder if there’s any difference.

  • @user50289 Welcome to Soft, go to Help and tour to understand how this community works and how to ask and deal with the answers and comments.

  • @user50289, I would like to add an addendum on Arraylist: here

Show 2 more comments

1 answer

2

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>();

How you defined the type of the variable List<String>, this is completely possible. If it were with the variable lista2, that would not be possible.

I won’t go into detail on this because there are many responses 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 cannot be instantiated, they serve only to define a contract in the classes that implement it.

Hence, you can’t do

List<String> lista = new List<String>(); // É impossível instanciar uma interface

However, it is completely 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.

Ex.:

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

An interface is a variable?
In object orientation, why interfaces are useful?
Abstract Class X Interface
In OOP, an interface can have attributes?
When to use Inheritance, Abstract Class, Interface or a Trait?

  • would like to add an Addendum on Arraylist: here

  • Sorry, I will remove and put in question. Sorry!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.