Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an Array into Set properly?

Tags:

java

set

I'm trying to add in Integer array into Set as following,

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

I'm getting some error telling as following,

myTest.java:192: error: no suitable constructor found for HashSet(List<int[]>)
    Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));
                       ^
constructor HashSet.HashSet(Collection<? extends Integer>) is not applicable
  (argument mismatch; inferred type does not conform to upper bound(s)
      inferred: int[]
      upper bound(s): Integer,Object)
constructor HashSet.HashSet(int) is not applicable
  (argument mismatch; no instance(s) of type variable(s) T exist so that List<T> conforms to int)
 where T is a type-variable:
T extends Object declared in method <T>asList(T...)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to        get full output
   1 error

Secondly, I also tries as following and still getting error,

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

How to add an Integer array into Set in Java properly ? Thanks.

like image 748
Arefe Avatar asked Dec 27 '15 05:12

Arefe


People also ask

Can we convert array into Set?

To convert array to set , we first convert it to a list using asList() as HashSet accepts a list as a constructor. Then, we initialize the set with the elements of the converted list.

Can we convert array to Set Java?

Converting an array to Set object The Arrays class of the java. util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.


1 Answers

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.

like image 79
Elliott Frisch Avatar answered Oct 06 '22 01:10

Elliott Frisch