3

Many times I'm operating in a function that returns a List type. For many types of errors or certain inputs it is invalid just to return an empty list which I normally do with the following:

return new ArrayList<DataType>();

Is that the best way or is there a better implementation of the List Interface to use for this situation? I should clarify that by "best" way I'm thinking from a performance perspective. I realize that any gains would be rather trivial but the OCD side of me is curious.

2
  • What does OCD stands for? Curious here too =) Commented Jan 28, 2015 at 23:37
  • @BonanzaOne Obsessive Compulsive Disorder. Commented Jan 28, 2015 at 23:43

1 Answer 1

14

There is a method of Collections specifically for this: Collections.emptyList(). This will return an empty, immutable List. You could replace the line in your code with this equivalent:

return Collections.<DataType>emptyList();
Sign up to request clarification or add additional context in comments.

3 Comments

As of 1.7- I didn't need to parameterize the return type. That is, return new Collections.emptyList() did not generate a warning.
@IcedDante Yes, you shouldn't need to most of the time—the compiler will figure it out for you. I just specified it explicitly for illustrative purposes.
@IcedDante Emphasizing: it wil return an immutable List. For example, you will get an Exception if you try to add something to the list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.