Why should the interface for a Java class be preferred?

后端 未结 10 1472
陌清茗
陌清茗 2020-11-22 05:43

PMD would report a violation for:

ArrayList list = new ArrayList();


The violation was \"Avoid using implementat

10条回答
  •  梦如初夏
    2020-11-22 06:26

    ArrayList and LinkedList are two implementations of a List, which is an ordered collection of items. Logic-wise it doesn't matter if you use an ArrayList or a LinkedList, so you shouldn't constrain the type to be that.

    This contrasts with say, Collection and List, which are different things (List implies sorting, Collection does not).

提交回复
热议问题