Java int[] array to HashSet

前端 未结 7 2168
感情败类
感情败类 2020-12-29 20:54

I have an array of int:

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

I need a typed set from it:

Set s;

If I do th

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 21:21

    Some further explanation. The asList method has this signature

    public static  List asList(T... a)
    

    So if you do this:

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

    or this:

    List 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 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 asList(int i...);
    

提交回复
热议问题