java 中如何 找出两个集合中的不重复的元素

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/27 22:13:50

java 中如何 找出两个集合中的不重复的元素
java 中如何 找出两个集合中的不重复的元素

java 中如何 找出两个集合中的不重复的元素
You can try to use Java's Set and Set's removeAll() method, for example:
import java.util.HashSet;
import java.util.Set;
public class Test {
\x09public static void main(String[] args) {
\x09\x09Set a = new HashSet();
\x09\x09Set b = new HashSet();
\x09\x09a.add(1);
\x09\x09a.add(2);
\x09\x09b.add(2);
\x09\x09b.add(3);
\x09\x09Set a1 = new HashSet();
\x09\x09Set b1 = new HashSet();
\x09\x09
\x09\x09a1.addAll(a);
\x09\x09b1.addAll(b);
\x09\x09
\x09\x09System.out.println("a1 as the clone of a:"+a1);
\x09\x09System.out.println("b1 as the clone of b:"+b1);
\x09\x09
\x09\x09a1.removeAll(b);
\x09\x09b1.removeAll(a);
\x09\x09
\x09\x09System.out.println("In a but not in b:"+a1);
\x09\x09System.out.println("In b but not in a:"+b1);
\x09}
}
Console output:
a1 as the clone of a:[1, 2]
b1 as the clone of b:[2, 3]
In a but not in b:[1]
In b but not in a:[3]