4

I am using the following code to convert a Set to int[]

Set<Integer> common = new HashSet<Integer>();
int[] myArray = (int[]) common.toArray();

the I got the following error:

 error: incompatible types: Object[] cannot be converted to int[]

What would be the most clean way to do the conversion without adding element one by one using a for loop? Thanks!

Edamame
  • 23,718
  • 73
  • 186
  • 320

3 Answers3

9

You usually do this:

Set<Integer> common = new HashSet<Integer>();
int[] myArray = common.stream().mapToInt(Integer::intValue).toArray();
xehpuk
  • 7,814
  • 3
  • 30
  • 54
7
Set<Integer> common = new HashSet<>();
int[] values = Ints.toArray(common);
s7vr
  • 73,656
  • 11
  • 106
  • 127
2

You cannot explicitly cast something into an array.

Do this:

Integer[] arr = new Integer[common.size()];
Iterator<Integer> iterator = common.iterator(); 
int i = 0;
while (iterator.hasNext()){
    arr[i++] = iterator.next();
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Tilak Madichetti
  • 4,110
  • 5
  • 34
  • 52