Why do we first declare subtypes as their supertype before we instantiate them?

前端 未结 12 946
轻奢々
轻奢々 2021-02-01 19:27

Reading other people\'s code, I\'ve seen a lot of:

List ints = new ArrayList();
Map map = new HashMap();
12条回答
  •  孤独总比滥情好
    2021-02-01 19:44

    When you at some point decide to use a different implementation, say:

    List ints = new LinkedList();
    

    instead of

    List ints = new ArrayList();
    

    this change needs to be done only at a single place.

    There is the right balance to strike:

    usually you use the type which gives you the most appropriate guarantees. Obviously, a List is also a Collection which is also something Iterable. But a collection does not give you an order, and an iterable does not have an "add" method.

    Using ArrayList for the variable type is also reasonable, when you want to be a bit more explicit about the need for fast random access by object position - in a LinkedList, a "get(100)" is a lot slower. (It would be nice if Java had an interface for this, but I don't think there is one. By using ArrayList, you disallow casting an array as list.)

提交回复
热议问题