List interface with different instantiations

3

What is the difference, advantages, disadvantages between?:

  • List a=new ArrayList();\suponiendo que introducire numeros enteros
  • ArrayList a=new ArrayList(); \suponiendo que introducire numeros enteros
  • ArrayList<Integer> a=new ArrayList<Integer>();
  • List <Integer> a=new ArrayList<Integer>();
  • Or are all of them equivalent?

    Note: instead of ArrayList it could also have been LinkedList or some other.

        
    asked by Michelle 28.08.2017 в 07:38
    source

    2 answers

    2

    The difference lies in what everything is:

    • List is an interface (extending the interface Collection )
    • ArrayList is a class (which implements the List interface )

    Although all the options you specify will work correctly, using the List interface has advantages over using the ArrayList implemented class because you could benefit from polymorphism in object-oriented programming.

    For example, if later on in your project you see that you need to change the implementation, if you have defined your variable as List you should not have much trouble changing from ArrayList to another type of class that implements the interface List ( LinkedList for example). That's why options 1 and 4 can be more advantageous.

    And now, define the type parameter from the list (options 3 and 4) or not define it (options 1 and 2) ... it will depend on what you want to do. If you define it, then the types will be validated at compile time, which can help you find errors, but it will give you less flexibility later.

    Since it seems clear that you are going to use Integer and not others, then maybe it is better for you to define the type (option 4), because it will make the code easier to maintain and debug.

        
    answered by 28.08.2017 / 14:14
    source
    0

    In principle they are all equivalent, that is, the difference between them does not affect you when compiling. But internally if there is a difference and that at run time, the list will be instantiated as Object.

    Anyway, I recommend you instantiate it as ArrayList, so everything is clearer.

    Greetings.

        
    answered by 28.08.2017 в 09:48