简体   繁体   English

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

[英]use for loop to visit all elements in a HashSet (Java)?

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 在for循环上,它说java.lang.ClassCastException: [I cannot be cast to java.lang.Integer

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 使用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 这里的第一个foreach对您来说已经足够了,如果您想按设置进行,请选择第二个for循环

您的集合包含Integer对象,因此在foreach循环中进行迭代时,应编写for (Integer i : collection) -这是因为基本类型int没有自己的Iterator实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM