使用for循环访问哈希集中的所有元素(Java)?
我将代码编写为:使用for循环访问哈希集中的所有元素(Java)?,java,loops,for-loop,hashset,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;
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:[我不能转换为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);
}
使用Java8
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对您来说已经足够了,如果您想按set进行设置,请使用第二个for循环您不能直接执行此操作,但您需要选择间接方法
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);
}
使用Java8
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循环,因为您的集合包含整数对象,所以在迭代foreach循环时,您应该为整数i:collection编写代码-这是因为基元类型int没有自己的迭代器实现。您的集合是containing Integer对象,因此在遍历foreach循环时,您应该为Integer i:collection编写代码-这是因为基本类型int没有自己的迭代器实现。已经回答了int和Integer不是同一类型。修复for中的类型,它应该可以工作。是的,谢谢!我已经基于这个想法编写了此代码。但是,我的代码中有一个错误。我想知道如何修复它。您需要像new HashSetIntStream.ofnums1.boxed.collectCollectors.toList这样的东西,您当前正在获取一个HashSet并使用一个原始类型,因此您也忽略了一个警告。@4castle。已应答的int和Integer不是同一类型。请修复for中的类型,它应该是work。是的,谢谢!我已经根据这个想法编写了这段代码。但是我的代码中有一个错误。我想知道如何修复它。您需要像new HashSetIntStream.ofnums1.boxed.collectCollectors.toList这样的东西,您当前正在获取一个HashSet并使用一个原始类型,因此您也忽略了一个警告。@4castle。