为什么有人在java中使用Collections.emptyList?
可能重复:
Collections.emptyList()与新实例
我试图了解创建列表的新实例之间的区别:
new ArrayList
和
Collections.emptyList();
据我所知,后者返回一个不可变列表。 这意味着无法添加,删除或修改它。 我想知道为什么会创建和不可变的emptyList? 有什么用? 谢谢
假设您必须返回一个集合,并且您不希望每次都创建几个对象。
interface Configurable { List getConfigurationList(); } // class which doesn't have any configuration class SimpleConfigurable implements Configurable { public List getConfigurationList() { return Collections.emptyList(); } }
返回空集合通常比返回null
更可取
不可变为允许可重用的实例。
Collections.emptyList将始终返回完全相同的单例实例。
这非常有效。
除此之外,可以在线程之间安全地共享不可变数据,并保证避免由于编码错误导致的奇怪副作用。 因此,它也不需要防御性副本。
我经常使用空列表作为Null对象 :这样可以避免检查null
。
我已经将Collections.emptyList
用于返回列表但使用没有意义的参数调用的方法。
例如,您可能希望根据日期访问流的不同部分的流处理应用程序。 您从流中查询项目的时间跨度,但如果该时间跨度中没有项目,则返回空列表。 抛出exception没有任何意义,因为查询没有任何问题。 返回null
也没有多大意义,因为所有调用代码都需要检查null
。
返回一个不可变的空列表允许调用代码很好地处理返回值,您不需要担心线程问题,因为不可变列表本质上是线程安全的。
避免不需要的NullPointerException。
在您的代码中,您可以返回正常的“空”ArrayList而不是返回null。 但是,通过这种方式,您将在每次执行时继续创建新对象(默认容量为10),这不是一种内存有效的方法。 如果返回emptyList,则会在每次调用时返回相同的实例。 这样,它可以更有效地避免不必要的NullPointerException。 以下是来自Javadoc for emptyList的剪辑:
/** * Returns the empty list (immutable). This list is serializable. * * This example illustrates the type-safe way to obtain an empty list: *
* List<String> s = Collections.emptyList(); *
* Implementation note: Implementations of this method need not * create a separate List object for each call. Using this * method is likely to have comparable cost to using the like-named * field. (Unlike this method, the field does not provide type safety.) * * @see #EMPTY_LIST * @since 1.5 */
- 无法在Eclipse Indigo中启动Tomcat 7.0
- 如何从JFileChooser检索UNC路径而不是映射驱动器路径
- 如何在spring中用IN子句执行查询?
- Java的ProcessBuilder在哪里执行命令?
- 同样的老故事:Tomcat DBCP + MySQL,MySQLNonTransientConnectionException:连接关闭后不允许任何操作
- Java编译平台文件编码问题
- “hadoop namenode -format”返回java.net.UnknownHostException
- Gson java.text.ParseException:无法解析的日期
- 在单个系统上运行客户端/服务器prog