对于集合中包装的对象实用方法 [英] Utility method for wrapping an object in a collection
问题描述
我正在寻找在Java核心类库的静态方法或其他一些常用的依赖 - $ P $的Apache pferably一员 - 执行以下操作:
I'm looking for a static method in the Java core libraries or some other commonly used dependency — preferably one of Apache — that does the following:
public static <T> Collection<T> wrap(final T object){
final Collection<T> collection = new ArrayList<T>();
collection.add(object);
return collection;
}
你知道这样的方法已经存在?因为我想这个问题是共同的,我不想重复它的解决方案。
Do you know where such a method already exists? Since I guess the problem is common, I don't want to duplicate it's solution.
推荐答案
java.util.Collections.singleton(对象)
会给你一个不变设置
。 singletonList
也是可用的。
java.util.Collections.singleton(object)
will give you an immutable Set
. singletonList
is also available.
效率较低 java.util.Arrays.asList(对象)
会给你一个可变的(可以使用 list.set(0,X) ;
),但非结构性改变的(不能添加或删除)列表
。这是一个有点贵,因为是创建客户端一个额外的数组。
Less efficiently java.util.Arrays.asList(object)
will give you a mutable (can use list.set(0, x);
), but non-structurally changeable (can't add or remove) List
. It is a bit more expensive as there is an extra array that is created client-side.
这篇关于对于集合中包装的对象实用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!