How to add an Array into Set properly?

You need to use the wrapper type to use Arrays.asList(T...)

Integer[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };
Set<Integer> set = new HashSet<>(Arrays.asList(arr));

or add the elements manually like

int[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };
Set<Integer> set = new HashSet<>();
for (int v : arr) {
    set.add(v);
}

Finally, if you need to preserve insertion order, you can use a LinkedHashSet.


myTest.java:192: error: no suitable constructor found for HashSet(List<int[]>)

Note that arrays in java are Objects so Arrays.asList(int[]) will internally consider int[] as a single element. So, <T> List<T> asList(T... a) will create List<int[]> instead of List<Integer> and so you can not create Set<Integer> from collection of array (not Integer elements).

Possible solutions could be, just use Integer(wrapper class) instead of int (primitive type).(Which is already stated by Elliott Frisch).

If you are using Java-8 and getting int[] and can not change to Integer[],

int[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };
Integer[] wrapper = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Set<Integer> set = new HashSet<Integer>(Arrays.asList(wrapper));

Moreover, as pointed out by Louis Wasserman, if you are using java-8 you can directly collect array elements to the Set.

Set<Integer> set = Arrays.stream(arr).boxed().collect(Collectors.toSet());

Since Java 8, you can use Stream.

int[] arr = { 2, 6, 4 , 2, 3, 3, 1, 7 };

Set<Integer> set = Arrays.stream(number).boxed().collect(Collectors.toSet());

This should work.

Tags:

Java

Set