collection vs list vs arrays as return type for EJB method

后端 未结 4 1027
情话喂你
情话喂你 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 03:02

    Collections in general are preferable over arrays, especially since Java5, where they were turned generic. This gives you type safety, and lots of potential extra features which aren't available in arrays (e.g. Set / Queue etc. behaviour) - these are in fact not directly comparable to arrays at all. Among collections, ArrayList is the direct analogy of an array, and - being implemented on top of an array - its performance is comparable to a native array.

    As for Collection vs List (or some other more specific interface), I personally would prefer the more specific interface, as the characteristics and behaviour of e.g. a List vs a Set is very different. In a well designed interface, you should know (and specify) in advance whether you return e.g. a Set, Dequeue or List. If you return a Collection, all your clients can do (apart from adding/removing elements) is to iterate through it, which may not be enough for them.

提交回复
热议问题