java 中如何 找出两个集合中的不重复的元素
来源:学生作业帮助网 编辑:作业帮 时间:2024/07/04 05:52:56
![java 中如何 找出两个集合中的不重复的元素](/uploads/image/z/6634751-23-1.jpg?t=java+%E4%B8%AD%E5%A6%82%E4%BD%95+%E6%89%BE%E5%87%BA%E4%B8%A4%E4%B8%AA%E9%9B%86%E5%90%88%E4%B8%AD%E7%9A%84%E4%B8%8D%E9%87%8D%E5%A4%8D%E7%9A%84%E5%85%83%E7%B4%A0)
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]