Hibernate query.list() method is returning empty list instead of null value

JavaHibernateCollectionsNullpointerexceptionReturn Value

Java Problem Overview


When there are no rows, both query.list() and criteria.list() are returning empty list instead of a null value.

What is the reason behind this?

Java Solutions


Solution 1 - Java

The reason is not to force null checks in client code, in consistency with Effective Java 2nd Edition, Item 43: Return empty arrays or collections, not nulls.

This makes the client code simpler and less error-prone (and most likely the method implementation as well).

> The null-return idiom is likely a holdover from the C programming language, in which array lengths are returned separately from actual arrays. In C, there is no advantage to allocating an array if zero is returned as the length.

Solution 2 - Java

It is consistant: a list is returned with all results, whether there are any or not.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionReddyView Question on Stackoverflow
Solution 1 - JavaPéter TörökView Answer on Stackoverflow
Solution 2 - JavaSjoerdView Answer on Stackoverflow