There are many cases in which we can return an empty object instead of null. This is usually preferable since it helps to eliminate one of the most common problem: NullPointerException
Following qualify as empty object :
- Empty String
- zero-length Array
- empty collection
Examples for empty object:-
- String str = "";
- int[] values = new int[0];
- List<Integer> list = new ArrayList<>();
Collections class contains several type-safe methods which return an empty collection
Collections.emptyList();
Collections.emptySet();
Collections.emptyMap();
by default, these methods are also immutable and serializable.
No comments:
Post a Comment