Is it better to use List or Collection?

前端 未结 8 693
失恋的感觉
失恋的感觉 2021-02-03 19:33

I have an object that stores some data in a list. The implementation could change later, and I don\'t want to expose the internal implementation to the end user. However, the us

相关标签:
8条回答
  • 2021-02-03 20:38

    It just depends, do you want your users to be able to index into the data? If yes, use List. Both are interfaces, so you're not leaking implementation details, really, you just need to decide the minimum functionality needed.

    0 讨论(0)
  • 2021-02-03 20:39

    When returning an implementation of an interface or class that is in a tall hierarchy, the rule of thumb is that the declared return type should be the HIGHEST level that provides the minimum functionality that you are prepared to guarantee to the caller, and that the caller reasonably needs. For example, suppose what you really return is an ArrayList. ArrayList implements List and Collection (among other things). If you expect the caller to need to use the get(int x) function, then it won't work to return a Collection, you'll need to return a List or ArrayList. As long as you don't see any reason why you would ever change your implementation to use something other than a list -- say a Set -- then the right answer is to return a List. I'm not sure if there's any function in ArrayList that isn't in List, but if there is, the same reasoning would apply. On the other hand, once you do return a List instead of a Collection, you have now locked in your implementation to some extent. The less you put in your API, the less restriction you put on future improvements.

    (In practice, I almost always return a List in such situations, and it has never burned me. But I probably really should return a Collection.)

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