JavaDeveloper
JavaDeveloper

Reputation: 5660

How to use empty list when we have an empty list anyways

This question is a bit hard to explain so please look at the increasingPath function in the code here. Now assuming the path does not exist, and arraylist pointPath with 0 size is returned. However I have read that we must use Collections.emptyList, but how do I use it in this scenario, when I already have a probably empty list called pointPath ? If not to use Collections.emptyList then when to use it ?

Upvotes: 0

Views: 75

Answers (2)

Igor Katkov
Igor Katkov

Reputation: 6380

Simply check

if (pointPath.isEmpty()){
    return Collections.emptyList();
}

The only difference from actually returning a your list that is accidentally empty is that Collections.emptyList() is immutable list. If that is not of any value to you, I'd return your real list. That way there is less code to read.

Upvotes: 1

dckuehn
dckuehn

Reputation: 2475

I think what you're supposed to do is use Collections.EmptyList for comparisons and returning.

for example:

if (pointPath.equals(Collections.emptyList()){
    return Collections.emptyList();
}

I don't think it changes how your program will execute, but it makes the code readable and self-documenting.

Upvotes: 2

Related Questions