Alex Rivera | Logout

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

Asked 2012-11-29T10:47:02.540
17

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.

Edit
Report

1 Answer

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...
answered 2012-11-29T11:00:02.913

Your Answer