Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems converting Set of Integers to int[] array

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.

like image 362
L-Samuels Avatar asked Aug 19 '11 15:08

L-Samuels


1 Answers

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.

like image 117
Thomas Avatar answered Oct 12 '22 14:10

Thomas