Reputation: 29448
I was trying to convert int
array to Set<Integer>
.
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
But the compiler doesn't accept the above code. It says: "The constructor HashSet(List) is undefined." Well, I thought that int
should be autoboxed.
I slightly modified the code, change int
to String
:
String[] arr = {"hello", "world"};
Set<String> s = new HashSet<String>(Arrays.asList(arr));
This code works okay.
I tried the following, change int
to Integer
:
Integer[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
This is passed the compilation.
My question is: why doesn't java compiler accept the first code?
Upvotes: 1
Views: 1418
Reputation: 360
In java Containers want "Objects" and primitives don't derive from Object. Generics allow you to pretend there is no wrapper, but you still pay the performance price of boxing. This is IMPORTANT to many programmers.
List list; That is also a reason why there are wrapper classes for primitive types:
int -> Integer
boolean -> Boolean
double -> Double
byte -> Byte etc...
Upvotes: 1
Reputation: 11917
Your problem is the call to Arrays.asList(arr)
. It has gotten confused by the use of a primitive array. Java treats primitives and objects differently.
asList only knows about arrays of objects, and in your case it is treating the entire array as a single element. That is, asList(arr)
is returning Set<int[]>
, such that the following is true:
Set<int[]> s = new HashSet<Integer>(ints);
Which is not what you meant.
There is no auto boxing of primitive arrays in Java. The quickest fix is to use Integer rather than int for the input array:
Integer[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3}; // java supports autoboxing when declaring an array
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
otherwise you will have to iterate and add the elements yourself.
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>();
for ( int v : arr ) {
s.add(v); // autoboxing of a single int is supported by Java, and happens here
}
Upvotes: 2
Reputation: 35557
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
Because your Set
is type Integer
(Object) and array
is type int
(primitive).
Read Arrays.asList()
Arrays.asList() // takes in put as Generics
Generics in Java
is not applicable to primitive
types as in int
. That's why you are getting this error.
Upvotes: 3