collection vs list vs arrays as return type for EJB method

后端 未结 4 1030
情话喂你
情话喂你 2021-02-02 02:21

I was recently told that collection should be preferred to List as the return value of an EJB method. The argument is that in general collection is more generic i.e. gives you t

4条回答
  •  灰色年华
    2021-02-02 02:53

    • Prefer collections over arrays; Use generics
    • Use interfaces instead of concrete classes

    Then you usually have 4 options: List, Set, Collection and Iterable. There it depends what is the semantics you want to include.

    • If it is an internal API - decide it based on the characteristics of the collection:
      • does it only hold unique items? Set
      • will clients need random access to it? List
      • will clients need to modify it (add, remove) (without the above two characteristics)? Collection
      • will clients just need to iterate it? Iterable
    • If it's a web service it doesn't matter - it is serialized the same way.

    (Note: there are some collection interfaces with more specific semantics: Queue, Deque, Map, Bag, Multiset, etc. - but it will be fairly obvious when you need to return them)

提交回复
热议问题