1

I have write the code as:

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> has1 = new HashSet(Arrays.asList(nums1)); 
        for (int i: has1)
            System.out.println(i);
        return nums1;
    }
}

num1: [1,2,4,2,3]
num2: [4,5,6,3]

On the for loop it says java.lang.ClassCastException: [I cannot be cast to java.lang.Integer

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Hanrun Li
  • 23
  • 1
  • 9
  • already answered http://stackoverflow.com/questions/12455737/how-to-iterate-over-a-set-hashset-without-a-iterator – Hector Oct 10 '16 at 03:33
  • `int` and `Integer` are not the same type. Fix the type in the `for` and it should work. – ajb Oct 10 '16 at 03:34
  • Yes, thank you! I have write this code based on the idea. However there is an error in my code. I want to know how to fix it. – Hanrun Li Oct 10 '16 at 03:35
  • You need something like `new HashSet<>(IntStream.of(nums1).boxed().collect(Collectors.toList()))`, you're currently getting a `HashSet` and using a raw-type so you're also ignoring a warning. – Elliott Frisch Oct 10 '16 at 03:35
  • @4castle [Raw types](http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html). – Elliott Frisch Oct 10 '16 at 03:37
  • Frisch, Thank you very much!!! It works!!! – Hanrun Li Oct 10 '16 at 03:39

2 Answers2

5

you cannot do this directly but you need to prefer a indirect approach

int[] a = { 1, 2, 3, 4 };
        Set<Integer> set = new HashSet<>();
        for (int value : a) {
            set.add(value);
        }
        for (Integer i : set) {
            System.out.println(i);
        }

using Java 8

 1) Set<Integer> newSet = IntStream.of(a).boxed().collect(Collectors.toSet());//recomended

    2)  IntStream.of(a).boxed().forEach(i-> System.out.println(i)); //applicable

here first foreach is sufficient for you and If you want to go by set, go with second for loop

bananas
  • 1,176
  • 2
  • 19
  • 39
0

Your collection is containing Integer objects, so while iterating through foreach loop, you should write for (Integer i : collection) - that is because primitive type int do not have its own Iterator implementation.

Wojtek
  • 1,288
  • 11
  • 16