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
  • 20,574
  • 59
  • 165
  • 291

3 Answers3

8

You usually do this:

Set<Integer> common = new HashSet<Integer>();
int[] myArray = common.stream().mapToInt(Integer::intValue).toArray();
xehpuk
  • 7,064
  • 2
  • 28
  • 50
7
Set<Integer> common = new HashSet<>();
int[] values = Ints.toArray(common);
s7vr
  • 69,355
  • 6
  • 87
  • 117
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
  • 15,514
  • 17
  • 42
  • 51
Tilak Maddy
  • 3,505
  • 2
  • 32
  • 49