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

问题描述

Java中使用 Collections.singletonList()有什么用?我知道它返回一个包含一个元素的列表。为什么我想要一个单独的方法来做到这一点?不变性如何在这里发挥作用?

What is the use of Collections.singletonList() in Java? I understand that it returns a list with one element. Why would I want to have a separate method to do that? How does immutability play a role here?

此方法是否有任何特殊的有用用例,而不仅仅是一种方便的方法?

Are there any special useful use-cases for this method rather than just being a convenient method?

推荐答案

说:

你问:

为方便起见...为了节省您必须编写一系列语句:

As a convenience ... to save you having to write a sequence of statements to:


  • 创建一个空列表对象

  • 添加一个元素,

  • 用不可变包装器包装它。

这是方法规范的一部分;见上文。

It is part of the specification of the method; see above.

显然,有些用例可以方便地使用 singletonList 方法。但我不知道你会如何(客观地)区分普通用例和特别有用用例...

Clearly, there are use-cases where it is convenient to use the singletonList method. But I don't know how you would (objectively) distinguish between an ordinary use-case and a "specially useful" one ...

这篇关于使用Java的Collections.singletonList()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:12