Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 7 API design best practice - return Array or return Collection

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.

like image 667
Shengjie Avatar asked Nov 29 '12 10:11

Shengjie


People also ask

Can API return array?

Each JSON object in your API should always have an immutable, strictly-defined set of fields between requests. The above is an excellent use-case for arrays. Just return an array and include the id inside each array element.

Can we return entire array in Java?

We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.


1 Answers

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.

like image 76
Marko Topolnik Avatar answered Nov 04 '22 04:11

Marko Topolnik