0

I put some numbers into a HashSet, then try to get an int[] using stream:

    HashSet set = new HashSet<Integer>();
    set.add(1);
    set.add(2);
    set.add(3);

    int[] ii = set.stream().mapToInt(i -> ((Integer)i).intValue()).toArray();

It works fine. My question is why I need to cast i into an Integer for it to work? If I don't cast, i stays an Object.

According to the docs, stream() should return a Stream<E>, where E in this case is Integer. That is why I did not anticipate the cast.

shmosel
  • 49,289
  • 6
  • 73
  • 138
Nick Lee
  • 5,639
  • 3
  • 27
  • 35
  • 2
    Look at the declared type of `set` - you're using the raw type. Was that intentional? If you used a `HashSet` as the declared type you may well find things work better. – Jon Skeet May 01 '17 at 06:58
  • My bad. A careless overlook. Thanks. – Nick Lee May 01 '17 at 16:40
  • Regarding the claim of duplication, if you know the answer, then it is a duplicate. But if you *don't* know the answer (and confused like I was), then it is actually a very different starting point. Imagine someone encountering the exact same problem as mine, who has no idea where it went wrong and does not suspect anything related to "raw type", would he have searched and found the other question? A definite NO. – Nick Lee May 01 '17 at 16:56
  • The first thing that should have given you a hint was the warning your compiler probably gave you. Warnings are your friend :) – Jon Skeet May 01 '17 at 17:34

1 Answers1

0

You have HashSet as RawType, thats why this problem is coming. Try to make this:

HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
int[] ii = set.stream().mapToInt(i -> (i).intValue()).toArray();
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45