Why does the Collections class contain standalone (static) methods, instead of them being added to the List interface?

前端 未结 5 1838
时光取名叫无心
时光取名叫无心 2021-02-19 11:41

For all the methods in Collections that take a List as their first argument, why aren\'t those methods simply part of the List interface?

My intuition is: given a List

5条回答
  •  无人及你
    2021-02-19 12:25

    It's certainly a judgement call at some level. I think the main trade-off to consider is this: When you add a method to an interface, every implementer of that interface must write code to implement it.

    If the semantics of that method are such that different implementations of the interface will best implement those semantics in very different ways, then it's better to put it in the interface. (Of course, if the semantics simply can't be defined in terms of other methods in the interface, then it must be its own method in the interface.)

    On the other hand, if the semantics are such that they can be defined in terms of other methods in the interface, and implementers of the interface will just tend to write the same code over and over again, then it's better to make a utility method that takes an instance of the interface as an argument.

提交回复
热议问题