簡體   English   中英

使用for循環訪問HashSet(Java)中的所有元素?

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

我將代碼寫為:

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]

在for循環上,它說java.lang.ClassCastException: [I cannot be cast to java.lang.Integer

您不能直接執行此操作,但需要使用間接方法

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);
        }

使用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

這里的第一個foreach對您來說已經足夠了,如果您想按設置進行,請選擇第二個for循環

您的集合包含Integer對象,因此在foreach循環中進行迭代時,應編寫for (Integer i : collection) -這是因為基本類型int沒有自己的Iterator實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM