15

I know this question has be asked before generic comes out. Array does win out a bit given Array enforces the return type, it's more type-safe.

But now, with latest JDK 7, every time when I design this type of APIs:

public String[] getElements(String type)
vs
public List<String> getElements(String type)

I am always struggling to think of some good reasons to return A Collection over An Array or another way around. What's the best practice when it comes to the case of choosing String[] or List as the API's return type? Or it's courses for horses.

I don't have a special case in my mind, I am more looking for a generic pros/cons comparison.

Shengjie
  • 12,336
  • 29
  • 98
  • 139
  • 2
    Are you having special case in mind? It really depends on what exactly you want, each has its own advantages and disadvantages – amit Nov 29 '12 at 10:50
  • No, I am more looking for a generic comparison, like what case Array works better, what case Collections wins out, the reasons of coz. – Shengjie Nov 29 '12 at 10:53
  • 3
    I can't think of any case where I would prefer an array over a collection except in situations where great performance is needed (so almost never). – Pablo Nov 29 '12 at 10:57
  • @Pablo: If you want to guarantee *mutability* (of course you can overcome it by sending/returning an `ArrayList`. – amit Nov 29 '12 at 10:58
  • possible duplicate of [API java 5 and more: should I return an array or a Collection?](http://stackoverflow.com/questions/225572/api-java-5-and-more-should-i-return-an-array-or-a-collection) – Ciro Santilli OurBigBook.com Jan 26 '15 at 12:27

5 Answers5

14

If you are writing a public API, then your clients will usually prefer collections because they are easier to manipulate and integrate with the rest of the codebase. On the other hand, if you expect your public API to be used in a highly performance-sensitive context, the raw array is preferred.

If you are writing this for your own use, it would be a best practice to start out with a collection type and only switch to an array if there is a definite performance issue involving it.

An array's element type can be determined at runtime through reflection, so if that particular feature is important to you, that would be another case to prefer an array.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
12

Here is a partial list

Advantages of array:

  • Fast
  • Mutable by nature
  • You know exactly "what you get" (what is the type) - so you know exactly how the returned object will behave.

Advantages of list:

  • Behavior varies depending on actual type returned (for example - can be mutable or immutable depending on the actual type)
  • Better hirerchy design
  • (Depending on actual type) might be dynamic size
  • More intuitive hashCode(), equals() - which might be critical if feeding to a hash based collection as a key.
  • Type safety:

    String[] arr1 = new String[5]; 
    Object[] arr2 = arr1;
    arr2[0] = new Object(); //run time error :(
    List<String> list1 = new LinkedList<String>();
    List<Object> list2 = list1; //compilation error :)
    
amit
  • 175,853
  • 27
  • 231
  • 333
  • 2
    Note that, due to the covariance of array types, they are not quite typesafe. Declare `void setFirst(Object[] xs, Object x);` and call `setFirst(new Integer[2], "a")`, compiles. – Marko Topolnik Nov 29 '12 at 11:06
  • @MarkoTopolnik: I tried to indicate it (in an edit a few minutes ago) as an advantage of list with a simplified example – amit Nov 29 '12 at 11:08
  • Yes, I see. Seems that I overlooked that point. The point stands out better when we use method declaration and invocation for the example. – Marko Topolnik Nov 29 '12 at 11:51
  • Another advantage of a list is that it can be very easily converted to an array with .toArray, whereas arrays cannot easily be converted to Lists. – Caelum Sep 17 '15 at 17:23
3

If I have a choice I would select the Collection because of the added behaviour I get for 'free' in Java.

Implement to Interfaces

The biggest benefit is that if you return the Collection API (or even a List, Set, etc) you can easily change the implementation (e.g. ArrayList, LinkedList, HashSet, etc) without needing to change the clients using the method.

Adding Behaviour

The Java Collections class provides many wrappers that can be applied to a collection including

  1. Synchronising a collection
  2. Making a collection immutable
  3. Searching, reversing, etc...
ramsinb
  • 1,985
  • 12
  • 17
0

When you are exposing a public API it makes much sense to return a Collection, as it makes life easier for the client by using all sorts of methods available on it. Client can always call toArray() if wants an array representation for special cases.

Also integration with other modules becomes easier as most API expect collection so that can work too.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
0

In my point of view, it depends on what the returned value will be used for.

If the returned value will be iterated into and nothing else, an array is the best choice but if the result will be manipulated, then go for the appropriate Collection.

But be careful because, for example, List should allow duplicates while Set should not, Stack should be LIFO while Queue should be FIFO and notice the SHOULD that I use because only the implementation can determine the real behavior.

Anyway, it really depends.

ncenerar
  • 1,517
  • 12
  • 25