【发布时间】:2020-02-03 19:33:30
【问题描述】:
所以我们的项目都是关于集合的,它应该显示并集、交集、差异,我对我的代码有疑问,因为在我们老师给我们的示例中,集合的元素已经给出并且在输出在并集和交集中没有“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);
}
输出:(教师给定的代码!)
两个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]
两个Set的交集:[null, 1, 4]
两个Set的差:[0,2,3]
【问题讨论】:
标签: java set-intersection set-difference