Java int []数组到HashSet< Integer> [英] Java int[] array to HashSet<Integer>

查看:194
本文介绍了Java int []数组到HashSet< Integer>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个int数组:

  int [] a = {1,2,3}; 

我需要一个类型化的集合:

 组<整数> S; 

如果我执行以下操作:

  s = new HashSet(Arrays.asList(a)); 

当然,我认为:

 列表与LT; INT [] GT; 

而我的意思是:

 列表与LT;整数> 

这是因为int是一个基元。如果我使用了String,所有的都可以工作:

  Set< String> s = new HashSet< String>(
Arrays.asList(new String [] {1,2,3}));



如何轻松,正确和简洁地从以下地点开始:

  A)int [] a ... 

  B)整数[] a ... 

谢谢!

解决方案

一些进一步的解释。 asList方法具有此签名

  public static< T>列表与LT; T> asList(T ... a)

所以如果你这样做的话:

 列表<整数> list = Arrays.asList(1,2,3,4)

或者这个:

 列表<整数> list = Arrays.asList(new Integer [] {1,2,3,4})

在这些情况下,我相信java能够推断出你想返回一个List,所以它填充了类型参数,这意味着它需要Integer参数来调用方法。由于它能够将int值整数转换为Integer,所以没关系。



然而,这不起作用

 列表与LT;整数> list = Arrays.asList(new int [] {1,2,3,4})

因为原始包装强制(即int []到Integer [])不是内置到语言中(不确定为什么他们没有这样做,但他们没有)。
$ b $因此,每个原始类型都必须作为自己的重载方法来处理,这是commons包所做的。即

  public static List< Integer> asList(int i ...); 


I have an array of int:

int[] a = {1, 2, 3};

I need a typed set from it:

Set<Integer> s;

If I do the following:

s = new HashSet(Arrays.asList(a));

it, of course, thinks I mean:

List<int[]>

whereas I meant:

List<Integer>

This is because int is a primitive. If I had used String, all would work:

Set<String> s = new HashSet<String>(
    Arrays.asList(new String[] { "1", "2", "3" }));

How to easily, correctly and succinctly go from:

A) int[] a...

to

B) Integer[] a ...

Thanks!

解决方案

Some further explanation. The asList method has this signature

public static <T> List<T> asList(T... a)

So if you do this:

List<Integer> list = Arrays.asList(1, 2, 3, 4)

or this:

List<Integer> list = Arrays.asList(new Integer[] { 1, 2, 3, 4 })

In these cases, I believe java is able to infer that you want a List back, so it fills in the type parameter, which means it expects Integer parameters to the method call. Since it's able to autobox the values from int to Integer, it's fine.

However, this will not work

List<Integer> list = Arrays.asList(new int[] { 1, 2, 3, 4} )

because primitive to wrapper coercion (ie. int[] to Integer[]) is not built into the language (not sure why they didn't do this, but they didn't).

As a result, each primitive type would have to be handled as it's own overloaded method, which is what the commons package does. ie.

public static List<Integer> asList(int i...);

这篇关于Java int []数组到HashSet&lt; Integer&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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