Java int 数组到HashSet
我有一个int数组:
int[] a = {1, 2, 3};
我需要一个类型集:
Set s;
如果我执行以下操作:
s = new HashSet(Arrays.asList(a));
当然,它认为我的意思是:
List
而我的意思是:
List
这是因为int是原始的。 如果我使用了String,那么一切都会起作用:
Set s = new HashSet( Arrays.asList(new String[] { "1", "2", "3" }));
如何轻松,正确,简洁地从:
A) int[] a...
至
B) Integer[] a ...
谢谢!
进一步解释。 asList方法具有此签名
public static List asList(T... a)
所以,如果你这样做:
List list = Arrays.asList(1, 2, 3, 4)
或这个:
List list = Arrays.asList(new Integer[] { 1, 2, 3, 4 })
在这些情况下,我相信java能够推断出你想要一个List,所以它填充了type参数,这意味着它需要Integer参数来调用方法。 因为它能够将值从int自动变换为整数,所以没关系。
但是,这不起作用
List list = Arrays.asList(new int[] { 1, 2, 3, 4} )
因为原始的包装器强制(即int []到Integer [])没有内置到语言中(不确定为什么他们没有这样做,但他们没有)。
因此,每个基本类型都必须按照自己的重载方法进行处理,这就是commons包的作用。 即。
public static List asList(int i...);
或者您可以轻松地使用Guava将int[]
转换为List
:
Ints.asList(int...)
asList
public static List
asList(int... backingArray) 返回由指定数组支持的固定大小列表,类似于
Arrays.asList(Object[])
。 该列表支持List.set(int, Object)
,但任何将值设置为null
尝试都将导致NullPointerException
。返回的列表维护写入或读取的
Integer
对象的值,但不保留标识。 例如,未指定list.get(0) == list.get(0)
对于返回的列表是否为真。
该问题提出了两个不同的问题:将int[]
转换为Integer[]
并从int[]
创建HashSet
。 使用Java 8流很容易做到这两点:
int[] array = ... Integer[] boxedArray = IntStream.of(array).boxed().toArray(Integer[]::new); Set set = IntStream.of(array).boxed().collect(Collectors.toSet()); //or if you need a HashSet specifically HashSet hashset = IntStream.of(array).boxed() .collect(Collectors.toCollection(HashSet::new));
您可以在Apache Commons中使用ArrayUtils:
int[] intArray = { 1, 2, 3 }; Integer[] integerArray = ArrayUtils.toObject(intArray);
另一种选择是使用Eclipse Collections中的原始集。 您可以轻松地将int[]
转换为MutableIntSet
为Set
或Integer[]
,如下所示,或者您可以使用MutableIntSet
,它将具有更高的内存效率和高性能。
int[] a = {1, 2, 3}; MutableIntSet intSet = IntSets.mutable.with(a); Set integerSet = intSet.collect(i -> i); // auto-boxing Integer[] integerArray = integerSet.toArray(new Integer[]{});
如果你想直接从int数组转到Integer数组并保留顺序,那么这将有效。
Integer[] integers = IntLists.mutable.with(a).collect(i -> i).toArray(new Integer[]{});
注意:我是Eclipse Collections的提交者