所以我们的项目全部是关于集合的,它应该显示并集,交集,差异,并且我对我的代码有疑问,因为在老师给我们的示例中,集合的元素已经存在给定并且在输出中,并集和交集中没有“空”结果,但是我们的挑战是让用户输入元素,并且在我的代码中,我的并集和交集中没有“空”结果。可以吗?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Set<Integer> a = new HashSet<Integer>();
a.addAll(Arrays.asList(new Integer[5]));
for () {
//scan code...
}
Set<Integer> b = new HashSet<Integer>();
b.addAll(Arrays.asList(new Integer[5]));
for () {
//scan code...
}
// UNION
Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("\nUnion of the two Set: ");
System.out.println(union);
// INTERSECTION
Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set: ");
System.out.println(intersection);
// DIFFERENCE
Set<Integer> difference = new HashSet<Integer>(a);
difference.removeAll(b);
System.out.print("Difference of the two Set: ");
System.out.println(difference);
}
输出:(老师给定的密码!)
两个Set [0、1、2、3、4、5、7、8、9]的结合
两个Set [0、1、3、4]的交集
两个Set [2,8,9]的区别
我的输出:
设置A:
3 4 2 1 0
设置B:
7 4 1 9 8
两个集合的组合:[null,0、1、2、3、4、7、8、9]
两个集合的交集:[null,1、4]
两个集合的区别:[0,2,3]
答案 0 :(得分:0)
由于代码中的这两行,您使用了空值:
a.addAll(Arrays.asList(new Integer[5]));
b.addAll(Arrays.asList(new Integer[5]));
只需删除这两行,您的代码就可以工作。
答案 1 :(得分:0)
我同意@theincrediblethor,但作为解释...
您正在初始化Set,就好像它是一个数组一样。最初,一个Set为空,并且一个数组未初始化。您不想将“空”整数[null,null,null,null,null]放入Set中,即使您在输入中添加了真正的Integer,它们也只会停留在该位置。
由于集合不允许重复,因此添加时会删除4个空Integer。
因此,您剩下1个null和所有输入。
答案 2 :(得分:0)
在您的行中
a.addAll(Arrays.asList(new Integer[5]));
new Integer [5]正在创建一个由5个null值组成的数组[null,null,null,null,null]
Arrays.asList()只是将其转换为5个空值的Collection(List)
a.addAll()将集合中的所有元素添加到集合中,并且由于值是唯一的,因此只添加一个空值
所以您只需要删除该行,与Set b相同
尝试此代码,您将逐步看到
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
Integer[] arr = new Integer[5];
System.out.println(Arrays.toString(arr));
Set<Integer> a = new HashSet<Integer>();
a.addAll(Arrays.asList(arr));
System.out.println(a);
a.add(1);
System.out.println(a);
}
}
它打印