Why should the interface for a Java class be preferred?

后端 未结 10 1339
陌清茗
陌清茗 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:28

    In general I agree that decoupling interface from implementation is a good thing and will make your code easier to maintain.

    There are, however, exceptions that you must consider. Accessing objects through interfaces adds an additional layer of indirection that will make your code slower.

    For interest I ran an experiment that generated ten billion sequential accesses to a 1 million length ArrayList. On my 2.4Ghz MacBook, accessing the ArrayList through a List interface took 2.10 seconds on average, when declaring it of type ArrayList it took on average 1.67 seconds.

    If you are working with large lists, deep inside an inner loop or frequently called function, then this is something to consider.

提交回复
热议问题