java - Collections.emptyList() instead of null check? -


if have used collection in class may instantiated many times, may resort following "idiom" in order save unnecessary object creations:

list<object> list = null;  void add(object object) {     if (list == null)         list = new arraylist<object>();      list.add(object); }  // somewhere else if (list != null)     (object object : list)          ; 

now wondering if couldn't eliminate null checks using collections.emptylist(), have alter if check in add() so:

if (list == collections.<object>emptylist())     list = new arraylist<object>(); 

is there better way handle other allocating new empty collection every time?

edit: clear, would like use collections.emptylist(), above check in add() really ugly... wondering if there's better way or whole other way of handling this.

in order save unnecessary object creations

that's bad idea litter code == null checks , other handling of corner cases (and presumably end in null pointer exceptions anyway)!

now wondering if couldn't eliminate null checks using collections.emptylist()

no, not really. emptylist() returns empty list. could

if (list.equals(collections.<object>emptylist())) 

but still throw nullpointerexception if list == null, it's still not you're after.

my recommendation: initialize list new arraylist<object>, or, if instance want return empty list method, use collections.emptylist() instead. (this returns same instance every time, no unnecessary object creation there either.)

and use .isempty() check if collection empty or not.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -