jmmut
jmmut

Reputation: 904

Can Collections.EMPTY_LIST **fail** compared to Collections.emptyList()?

I know similar things have been asked before, but I didn't find any explanation as to why the type safety (provided by the method) matters in an empty immutable list.

Even though I always try to be type/generics correct, I would like to understand real cases when using the constant will cause an error that the method would prevent.

The worst consequence I found is that the method avoids a compilation error in specific cases but otherwise it just avoids a warning, which (according to my understanding) is not a big deal in practice: although I don't know the exact difference in the JVM, I know loosely that generics are used at compile time and then the types are erased and replaced by casts.

So, to wrap up, any example where an EMPTY_LIST is a Bad Idea (TM)?

Upvotes: 0

Views: 267

Answers (1)

maaartinus
maaartinus

Reputation: 46382

You're right, there's no risk of using EMPTY_LIST per se. However, you get a warning. Ignoring warnings is a risk, as one day you surely ignore one which didn't wan't to be ignored.

You can @SuppressWarnings, but then you either place the annotation on your method (or even class) and you're back to point one.

Or you create a local variable and annotate it. This is pretty verbose.

Or you create a tiny method returning the field and annotate it. Guess what Collections.emptyList() does.

Upvotes: 1

Related Questions