本文介绍了为什么有人在java中使用Collections.emptyList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I尝试理解使用以下方式创建列表的新实例之间的区别:

I was trying to understand the difference between create a new instance of a list using:

new ArrayList<X>

Collections.emptyList();

根据我的理解,后者返回一个不可变的列表。这意味着不可能添加,删除或修改它。
我想知道为什么会创建和不可变的emptyList?有什么用?
感谢

As I understood, the later returns an immutable list. That means that it is not possible to add,delete, or modify it.I want to know why one would create and immutable emptyList ? what is the use?thanks

推荐答案

假设你必须返回一个集合而你不想创建几个对象时间。

Say you have to return a collection and you don't want to creating a couple of objects each time.

interface Configurable {
    List<String> getConfigurationList();
}

// class which doesn't have any configuration
class SimpleConfigurable implements Configurable {
    public List<String> getConfigurationList() { return Collections.emptyList(); }
}



返回空集合通常比返回 null

这篇关于为什么有人在java中使用Collections.emptyList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 19:40