collection vs list vs arrays as return type for EJB method

后端 未结 4 1091
情话喂你
情话喂你 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:58

    First, it is not an issue only with EJB. This applies to all method definitions.

    In fact, the same is also said of the definition of parameters and variables:

     List myList = new ArrayList();
    

    The broader the definition that is made, the more freedom at the time of implementation. Say that I define:

     public class Numbers {
       public ArrayList getPrimesUnder(int N) {
       }
     }
    

    Let's say that I find that I can use someone's else library method to do that, but it returns a Vector instead of an ArrayList. Now, I'll have to risk breaking code that calls to my method or I'll have to copy the data from the Vector to an ArrayList. If I had defined the return type as List, I could return any instance of it.

    Why not use Collection in this case? Because List is an specialization of Collection that is ordered. If I want to return my results ordered, then I'll use List. If they are not ordered, then Collection suits better.

提交回复
热议问题