用于循环来访问HashSet(Java)中的所有元素?

Han*_* Li 1 java loops for-loop hashset

我把代码编写为:

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]
Run Code Online (Sandbox Code Playgroud)

在for循环中它说 java.lang.ClassCastException: [I cannot be cast to java.lang.Integer

emo*_*nas 5

你不能直接这样做,但你需要更喜欢间接的方法

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);
        }
Run Code Online (Sandbox Code Playgroud)

使用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
Run Code Online (Sandbox Code Playgroud)

这里首先foreach对你来说已经足够了,如果你想按套装去,那就去第二个循环