Java 如何快速方便地创建一个单元素数组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20358883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to quickly and conveniently create a one element arraylist
提问by David T.
Is there a Utility method somewhere that can do this in 1 line? I can't find it anywhere in Collections
, or List
.
是否有可以在 1 行中执行此操作的实用程序方法?我在Collections
, 或 中的任何地方都找不到它List
。
public List<String> stringToOneElementList(String s) {
List<String> list = new ArrayList<String>();
list.add(s);
return list;
}
I don't want to re-invent the wheel unless I plan on putting fancy rims on it.
我不想重新发明轮子,除非我打算在上面装上花哨的轮辋。
Well... the type can be T
, and not String
. but you get the point. (with all the null checking, safety checks...etc)
嗯...类型可以是T
,而不是String
。但你明白了。(所有的空检查,安全检查......等)
采纳答案by Elliott Frisch
Fixed size List
固定尺寸 List
The easiest way, that I know of, is to create a fixed-size single element List
with Arrays.asList(T...)
like
据我所知,最简单的方法是创建一个固定大小的单个元素List
,Arrays.asList(T...)
例如
// Returns a List backed by a varargs T.
return Arrays.asList(s);
Variable size List
可变尺寸 List
If it needs vary in size you can construct an ArrayList
and the fixed-sizeList
like
如果它需要不同的大小,您可以构建一个ArrayList
和固定大小的List
类似
return new ArrayList<String>(Arrays.asList(s));
and (in Java 7+) you can use the diamond operator <>
to make it
并且(在 Java 7+ 中)您可以使用菱形运算符<>
来制作它
return new ArrayList<>(Arrays.asList(s));
Single Element List
单元素列表
Collections can return a list with a single element with list being immutable:
集合可以返回一个包含单个元素的列表,列表是不可变的:
Collections.singletonList(s)
The benefit here is IDEs code analysis doesn't warn about single element asList(..) calls.
这里的好处是 IDE 代码分析不会警告单个元素 asList(..) 调用。
回答by SLaks
Very simply:
很简单:
Arrays.asList("Hi!")
回答by rgettman
You can use the utility method Arrays.asList
and feed that result into a new ArrayList
.
您可以使用实用程序方法Arrays.asList
并将结果提供给新的ArrayList
.
List<String> list = new ArrayList<String>(Arrays.asList(s));
Other options:
其他选项:
List<String> list = new ArrayList<String>(Collections.nCopies(1, s));
and
和
List<String> list = new ArrayList<String>(Collections.singletonList(s));
ArrayList(Collection)
constructor.Arrays.asList
method.Collections.nCopies
method.Collections.singletonList
method.
With Java 7+, you may use the "diamond operator", replacing new ArrayList<String>(...)
with new ArrayList<>(...)
.
在 Java 7+ 中,您可以使用“菱形运算符”,替换new ArrayList<String>(...)
为new ArrayList<>(...)
.
Java 9
爪哇 9
If you're using Java 9+, you can use the List.of
method:
如果您使用的是 Java 9+,则可以使用以下List.of
方法:
List<String> list = new ArrayList<>(List.of(s));
Regardless of the use of each option above, you may choose not to use the new ArrayList<>()
wrapper if you don't need your list to be mutable.
不管上面的每个选项如何使用,new ArrayList<>()
如果你不需要你的列表是可变的,你可以选择不使用包装器。
回答by user167019
The other answers all use Arrays.asList()
, which returns an unmodifiable list (an UnsupportedOperationException
is thrown if you try to add or remove an element). To get a mutable list you can wrap the returned list in a new ArrayList
as a couple of answers point out, but a cleaner solution is to use Guava'sLists.newArrayList()(available since at least Guava 10, released in 2011).
其他答案都使用Arrays.asList()
,它返回一个不可修改的列表(UnsupportedOperationException
如果您尝试添加或删除元素,则会抛出 an )。要获得可变列表,您可以将返回的列表包装在一个 new 中,ArrayList
正如几个答案所指出的那样,但更简洁的解决方案是使用Guava 的Lists.newArrayList()(至少从 2011 年发布的Guava 10 开始可用)。
For example:
例如:
Lists.newArrayList("Blargle!");
回答by Stein
Yet another alternative is double brace initialization, e.g.
另一种选择是双括号初始化,例如
new ArrayList<String>() {{ add(s); }};
but it is inefficient and obscure. Therefore only suitable:
但它是低效和晦涩的。因此只适合:
- in code that doesn't mind memory leaks, such as most unit tests and other short-lived programs;
- and if none of the other solutions apply, which I think implies you've scrolled all the way down here looking to populate a different type of container than the ArrayList in the question.
- 在不介意内存泄漏的代码中,例如大多数单元测试和其他短期程序;
- 如果其他解决方案都不适用,我认为这意味着您已经一直向下滚动,希望填充与问题中的 ArrayList 不同类型的容器。
回答by Andrew
Collections.singletonList(object)
the list created by this method is immutable.
此方法创建的列表是不可变的。
回答by Marko Jurisic
With Java 8 Streams:
使用 Java 8 流:
Stream.of(object).collect(Collectors.toList())
or if you need a set:
或者如果你需要一套:
Stream.of(object).collect(Collectors.toSet())
回答by vegemite4me
Seeing as Guava gets a mention, I thought I would also suggest Eclipse Collections(formerly known as GS Collections).
看到 Guava 被提及,我想我还建议使用Eclipse Collections(以前称为 GS Collections)。
The following examples all return a List
with a single item.
以下示例都返回List
带有单个项目的 a。
Lists.mutable.of("Just one item");
Lists.mutable.with("Or use with");
Lists.immutable.of("Maybe it must be immutable?");
Lists.immutable.with("And use with if you want");
There are similar methods for other collections.
其他集合也有类似的方法。