当我们创建空的不可变列表/集合/映射时,是否有任何实际的应用程序/用例 [英] Is there any practical application/use case when we create empty immutable list / set / map

查看:125
本文介绍了当我们创建空的不可变列表/集合/映射时,是否有任何实际的应用程序/用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 9提供了一种创建空不可变List,set和Map的方法。

Java 9 provides as a way to create Empty immutable List, set and Map.

List list = List.of(); 
Set set = Set.of(); 
Map map = Map.of();

但是我无法理解创建空的不可变列表/ set /的实际用例是什么map。

But I am not able understand what is the actual use case of creating an empty immutable list / set / map.

请帮我理解一个空的不可变列表/ set / map的实际用例。

Please help me to understand the actual use case of an empty immutable list / set / map.

推荐答案

在Java 9之前,有 Collections.emptyList() Collections.emptySet() Collections.emptyMap(),它们明确且专门用于生成不可修改的空集合。那个 List.of() 。也可以这样做是他们的API的内部一致性问题,而不是一个革命性的新功能。

Well before Java 9, there were Collections.emptyList(), Collections.emptySet(), and Collections.emptyMap(), which are explicitly and solely dedicated to producing unmodifiable empty collections. That List.of() etc. can also do this is a matter of internal consistency of their API, not a revolutionary new feature.

但你的主要问题似乎是


请帮助我理解一个空的不可变
列表/ set / map的实际用例。

Please help me to understand the actual use case of an empty immutable list / set / map.

这实际上是三个问题:


  1. 有什么用例空集合?

空集合很有用,因为它们是真实数据和算法中出现的情况的自然表示。例如,到目前为止哪些乘客已经办理登机手续?什么都没有。哪些任务等待发送?我可以无休止地继续。

Empty collections are useful because they are natural representations of situations that occur in real-world data and algorithms. For example, "Which passengers have checked in so far?" when none have. Which tasks are waiting to be dispatched? I could continue endlessly.

不可修改的集合有哪些用例?

可以传递对不可修改集合的引用,而不必担心集合将被修改(无论如何都要通过该引用)。请注意,假设不可修改性被适当记录,所有参与者在共享该对象时可以依赖它不要改变。除此之外,这对于安全地共享集合(以及其他不可修改的对象)而不复制它们非常重要。

A reference to an unmodifiable collection can be passed around without fear that the collection will be modified (via that reference, anyway). Note well that supposing the unmodifiability is appropriately documented, all participants in sharing that object can rely on it not to change. Among other things, this is important for safely sharing collections (and other unmodifiable objects) without making copies of them.

在哪些用例中它们的交集?

空集合在现实世界的数据和算法中自然发生,因此大多数不可修改集合的用例都包含空集合。

Empty collections occur naturally in real-world data and algorithms, so most use cases for unmodifiable collections are inclusive of empty collections.






另外,你没有问,但也许可以忽略它,尽管你不能将对象添加到不可修改的空集合中,您可以将其与非空集合一起替换,或者在下次提供非空集合时使用,或者类似。


Additionally, you did not ask but are perhaps overlooking that although you cannot add objects to an unmodifiable empty collection, you can replace it altogether with a non-empty collection, or serve up a non-empty collection the next time, or similar.

这篇关于当我们创建空的不可变列表/集合/映射时,是否有任何实际的应用程序/用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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