I have no problems converting a Set of Strings to 开发者_如何转开发a string[] array, but I'm having problems doing so with converting a Set of Integer to an int[] array. How can I convert the Integers to its primitive?
I cannot seem to find any related questions. Any quick suggestions that can help?
Sometimes, autoboxing cannot be used, as in the case of arrays. I don't think an array of integers will automatically be converted to an array of ints.
string[]
doesn't exist, I guess you mean String[]
.
For converting a Set<Integer>
to int[]
you'd have to iterate over the set manually.
Like this:
Set<Integer> set = ...;
int[] arr = new int[set.size()];
int index = 0;
for( Integer i : set ) {
arr[index++] = i; //note the autounboxing here
}
Note that sets don't have any particular order, if the order is important, you'd need to use a SortedSet
.
This is why Guava has an Ints.toArray(Collection<Integer>)
method, returning int[]
.
With java 8:
Set<Integer> set = new HashSet<>();
// TODO: Add implement for set
int[] array = set.stream().mapToInt(Integer::intValue).toArray();
I guess the problem is that Set<Integer>.toArray
converts to Integer[]
, rather than int[]
. So you have no simple way: you need to iterate through the set manually and add its elements to the int array. Converting an individual Integer
to int
is handled by autoboxing in Java 5 and above.
This should work, assuming auto unboxing!
Set<Integer> myIntegers; // your set
int[] ints = new int[myIntegers.size()];
int index = 0;
for(Integer i : myIntegers){
ints[index++] = i;
}
you can call the
Integer.intValue();
function...
lemme know more specifics of what you need :)
If you use Java 5+ Autoboxing should take care of this...!
What error do you get?
edit: ok i see..
Like other said:
loop on your Set and just put the Integer inside the int[], autoboxing should convert it.
精彩评论