【问题标题】:use for loop to visit all elements in a HashSet (Java)?使用 for 循环访问 HashSet (Java) 中的所有元素?
【发布时间】:2017-02-18 10:35:20
【问题描述】:

我把代码写成:

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

【问题讨论】:

  • intInteger 不是同一类型。修复 for 中的类型,它应该可以工作。
  • 好的,谢谢!我已经根据这个想法编写了这段代码。但是我的代码中有一个错误。我想知道如何解决它。
  • 你需要像new HashSet&lt;&gt;(IntStream.of(nums1).boxed().collect(Collectors.toList())) 这样的东西,你目前正在获得HashSet&lt;int[]&gt; 并使用原始类型,所以你也忽略了警告。
  • @4castle Raw types.

标签: java loops for-loop hashset


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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循环

    【讨论】:

      猜你喜欢
      • 2016-02-12
      • 2020-04-14
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2016-03-11
      • 2019-06-02
      • 2014-05-21
      相关资源
      最近更新 更多