Doubt over reference when instantiating an object

0

I have a question regarding the creation of objects, I will give 3 examples:

  • List<> nuevaLista = new ArrayList<>();
  • ArrayList<> nuevaLista= new ArrayList<>();
  • List <> nuevaLista = new LinkedList<>();
  • I know that List is an interface , and that any class that implements List should implement its abstract methods , but in this case, nuevaLista , How can it be a variable of type List if this is not a class?

    Out of that doubt, I read that in 1 and 3, nuevaLista can only implement methods of the interface List , then what is the difference between instantiating it as ArrayList or LinkedList or any class that implements List ?

    Thankful for your answers.

        
    asked by Christian 04.08.2018 в 00:06
    source

    3 answers

    1

    When you define List < > new list; you are declaring a variable of type List < > that can refer to objects of all classes that inherit from the List < & gt ;. This is called polymorphism.

    Therefore, in your first new example, List can refer to instances of objects of different classes (all those that implement List < >) and in the second example newList can only point to objects of class ArrayList < > (to objects of his daughter classes, if he had them, too).

    What can not be done in Java is to instantiate interfaces or abstract classes, but you can have a reference / variable that has one of them as a type. As I said before, this allows to make use of the polymorphism.

        
    answered by 04.08.2018 в 05:43
    0

    It can be done because LinkedList implements List as well as ArrayList, that you can check in the Java API

        
    answered by 04.08.2018 в 00:27
    0

    LinkedList as they said List as well as ArrayList em> , but unlike one another LinkedList is implemented with a double-linked list, instead ArrayList with an array that dynamically doubles its size when more space is needed.

    • Therefore we can consider that LinkedList for example allows me to delete or add elements with a complexity of O (1) while an ArrayList in O (n).

    • But for the search ArrayList is more efficient since it has a complexity of O (1) and LinkedList of O (n).

    Conclusion: They are different implementations for the same purpose, so depending on the use you want to give you will choose one or the other.

    I hope it helps you!

    Greetings! :)

        
    answered by 04.08.2018 в 02:14