LinkedList in Java

1

First, I have a LinkedList called LinkedEventos.

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

Subsequently, I have an assignment LinkedEventos = Compra; . Does anyone know to tell me what such an assignment accomplishes taking into account that to add an element from a LinkedList, should I use the add method and therefore such an assignment is not an addition in the list? Also, can someone tell me the difference between the LinkedList<Eventos> LinkedEventos = new LinkedList<Eventos>(); statement and List<Eventos> LinkedEventos = new LinkedList<Eventos>(); ? Thank you.

    
asked by anonymous 03.03.2017 / 19:40

1 answer

1

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

See 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);
    }
}

Output:

  

[purchase1, purchase2]
  [linkedevento1, linkedevento2]
  [compra1, compra2, compra3]
  [buy1, buy2, buy3]

Code running on Ideone .

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

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

    
03.03.2017 / 20:56