Collections.emptyList()而不是null检查? [英] Collections.emptyList() instead of null check?

查看:3037
本文介绍了Collections.emptyList()而不是null检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在某个类中有一个很少使用的集合,可能会被实例化多次,我有时可以使用以下成语,以便节省不必要的对象创建:

  List< Object> list = null; 

void add(Object object){
if(list == null)
list = new ArrayList< Object>();

list.add(object);
}

//其他地方
if(list!= null)
for(Object object:list)
;

现在我想知道是否不能使用集合.emptyList(),但是我必须改变 add()中的if检查:

  if(list == Collections.< Object> emptyList())
list = new ArrayList< Object>

有没有更好的办法来处理这个,而不仅仅是每次分配一个新的空集合? p>

EDIT:只是为了清楚,我希望使用Collections.emptyList() add()真的很丑陋...我想知道是否有更好的方法来做,甚至一个其他的方式处理这个。

解决方案


这是一个很糟糕的想法,将废弃你的代码与 == null 检查和其他处理的角落情况(可能结束在空指针异常)


现在我想知道如果我不能使用 Collections.emptyList()


emptyList()返回一个空列表。您可以 执行

$ <$ p

  if(list.equals(Collections。< Object> emptyList )

但是如果 list == null ,所以它仍然不是你的后。



我的建议:总是初始化列表 new ArrayList< Object& ,或者,如果你想从方法返回一个空列表,请改用 Collections.emptyList()。 (这每次都返回相同的实例,所以没有不必要的对象创建。)



然后使用 .isEmpty()以检查集合是否为空。


If I have a rarely used collection in some class which may be instantiated many times, I may sometimes resort to the following "idiom" in order to 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)
    for (Object object : list)
         ;

Now I was wondering if I couldn't eliminate those null checks using Collections.emptyList(), however then I would have to alter the if check in add() like so:

if (list == Collections.<Object>emptyList())
    list = new ArrayList<Object>();

Is there a better way to handle this other than just allocating a new empty collection every time?

EDIT: just to be clear, I would like to use Collections.emptyList(), but the above check in add() is really really ugly... I was wondering if there's a better way to do it or even a whole other way of handling this.

解决方案

in order to save unnecessary object creations

That's a really bad idea which will litter your code with == null checks and other handling of corner cases (and presumably end up in null pointer exceptions anyway)!

Now I was wondering if I couldn't eliminate those null checks using Collections.emptyList()

No, not really. emptyList() returns an empty list. You could do

if (list.equals(Collections.<Object>emptyList()))

but that will still throw a NullPointerException if list == null, so it's still not what you're after.

My recommendation: Always initialize the list to new ArrayList<Object>, or, if you for instance want to return an empty list from a method, use Collections.emptyList() instead. (This returns the same instance every time, so no unnecessary object creation there either.)

And then use .isEmpty() to check if a collection is empty or not.

这篇关于Collections.emptyList()而不是null检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆