Linkedlist in Java

Asked

Viewed 533 times

1

First of all, I have a Linkedlist called Linkedeventos.

LinkedList<Eventos> LinkedEventos = new LinkedList<Eventos>();

Then I have an assignment LinkedEventos = Compra;. Someone can tell me what such an assignment does, taking into account that, to add an element of a Linkedlist, I must use the method add and therefore such an assignment is not an addition to the list? Also, can anyone tell me the difference between the statement LinkedList<Eventos> LinkedEventos = new LinkedList<Eventos>(); and List<Eventos> LinkedEventos = new LinkedList<Eventos>();? Thank you.

  • In doing LinkedEventos = Compra; you are making the variable LinkedEventos reference the same as the variable Compra. In the second case you are creating a supertype variable List instead of LinkedList: Why create an object using the superclass?

  • Thank you very much.

  • I believe that performance does not vary, it is more about code maintainability.

1 answer

1


In doing LinkedEventos = Compra; you are making the variable LinkedEventos reference the same as the variable Compra. From that moment any modification you make to the object referenced by the variable Compra will be reflected in the variable LinkedEventos, since now both reference the same object.

Take the example:

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        LinkedList<String> compras = new LinkedList<String>();
        LinkedList<String> linkedEventos = new LinkedList<String>();

        compras.add("compra1");
        compras.add("compra2");
        linkedEventos.add("linkedevento1");
        linkedEventos.add("linkedevento2");

        System.out.println(compras);
        System.out.println(linkedEventos);

        linkedEventos = compras; //aqui as variaveis passam a referenciar o mesmo objeto
        compras.add("compra3");

        //pode-se ver que as variaveis agora possuem o mesmo conteudo
        System.out.println(compras);
        System.out.println(linkedEventos);
    }
}

Exit:

[buy1, buy2]
[linkedevento1, linkedevento2]
[buy1, buy2, buy3]
[buy1, buy2, buy3]

Code working on Ideone.

In the second part of your question you are creating a supertype List variable instead of Linkedlist. It can be said that it is duplicated:

But basically doing it the way List<Eventos> LinkedEventos = new LinkedList<Eventos>(); you are making use of polymorphism, it is better to do so because you will be programming for interface instead of programming for implementation.

Browser other questions tagged

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