What is the difference between declaring List vs ArrayList?

前端 未结 7 1902
北荒
北荒 2020-12-20 15:41
List mylist = new ArrayList();

ArrayList mylist2 = new ArrayList();

I am wondering wha

相关标签:
7条回答
  • 2020-12-20 16:22

    First one is called coding to interfaces.

    Using the List reference through out your code you can update the concrete implementation to something else like a LinkedList without breaking your client code.

    0 讨论(0)
  • 2020-12-20 16:27

    Always code to the interface.

    (Car analogy alert)

    You walk into Hertz Rent-a-Car. You say, I want an IVehicle. They say, "well, what kind of IVehicle?" You don't care. So they give you a DumpTruck. But you don't want a dump truck, you want something compact. You want an ICompact that extends IVehicle. So they give you a motorcycle. "No!" you exclaim, "I want an ICar!" "What kind of ICar?" they ask. "I don't care!" you exclaim. So they give you a FordCar, and you live happily ever after.

    Does that clear it up?

    0 讨论(0)
  • 2020-12-20 16:28

    In your statement 1, since you are referring mylist as List<Integer> while it is still ArrayList<Integer>, hence you can use the methods available in the List interface ONLY. This is better statement, if you are using cross class.method functionality.

    Also any method accepting List<Integer> can accept any of the implementation classes of List e.g. LinkedList<Integer> or your custom implementation class.

    Your second statement, creates and references the object as ArrayList<Integer> ONLY. Some people perefer it when mylist is to be used locally in the method.

    0 讨论(0)
  • 2020-12-20 16:29

    For myList, you will only be able to invoke methods of the List interface.

    For example, you cannot invoke the method ensureCapacity on myList.

    0 讨论(0)
  • 2020-12-20 16:36

    You can think of it as polymorphism.

    List<Integer> mylist declares it to be a List, but it doesn't have to be an ArrayList - JVM just knows that it implements the List interface.

    ArrayList<Integer> mylist2 declares it to be an ArrayList, so JVM knows that not only is it a List, it's an ArrayList in particular.

    0 讨论(0)
  • 2020-12-20 16:37

    I know that List is an interface that ArrayList class implements.

    That's exactly the difference :)

    When you're using the two variables (mylist) and (mylist2) in code, you would have access to any methods that ArrayList defines that aren't part of the basic List interface only on mylist2.

    0 讨论(0)
提交回复
热议问题