所以我们的项目都是关于集合的,它应该显示并集,交集,差异,我对我的代码有疑问,因为在老师给我们的例子中,集合的元素已经给出了,在输出中,并集和交集中没有"null“结果,但我们的挑战是让元素成为用户输入,而在我的代码中,我的并集和交集中有一个"null”结果。这样可以吗?
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);
}输出:(老师给出的代码!)
两个Set0,1,2,3,4,5,7,8,9的并集
两个Set0,1,3,4的交集
两个Set2、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
发布于 2019-10-06 10:25:31
因为您的代码中有以下两行,所以您会得到null:
a.addAll(Arrays.asList(new Integer[5]));
b.addAll(Arrays.asList(new Integer[5]));只需删除这两行,您的代码就应该可以工作了。
发布于 2019-10-06 10:36:21
我同意“不可思议的爱”,但作为一个解释...
您正在初始化一个集合,就好像它是一个数组一样。最初,集合是空的,数组是未初始化的。你不想把“空的”整数null,null放在集合中,即使你把真正的整数加到输入上,它们也会留在那里。
由于集合不允许重复,因此在添加时删除4个空整型。
所以你只剩下1个null和你所有的输入。
发布于 2019-10-06 11:11:09
在你的队伍里
a.addAll(Arrays.asList(new Integer[5]));新的Integer5正在创建一个包含5个空值的数组
Arrays.asList()只是将其转换为一个包含5个空值的集合(列表
a.addAll()将集合中的所有元素添加到集合中,由于值是唯一的,因此只需添加一个null
因此,您只需删除该行,集合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);
}
}它打印出来

https://stackoverflow.com/questions/58253726
复制相似问题