Java 比较两个集合
Java的Collection Framework提供了一个名为Set的接口,它扩展了Collection接口,用于存储唯一的元素。它描述了数学集合的特征。因此,它允许我们执行数学集合上的所有操作,如并集、比较、交集等。本文的目的是编写Java程序来比较两个集合。对于两个集合的比较操作,Java提供了一个内置的方法’equals()’,我们将在下一节中讨论。
Java程序比较两个集合
我们将在我们的Java程序中使用以下类和方法来比较两个集合 –
TreeSet类
由于Set是一个接口,我们无法直接使用它的功能。为此,我们需要实现Set接口的TeeSet类,这意味着它可以访问Set的所有方法。它以树形结构存储所有元素,并且像Set一样,它不允许存储重复的元素。
equals()方法
它是Set的一个方法,用于检查两个给定的集合是否包含相同数量和类型的对象,以相同的顺序。如果两个集合都满足条件,则返回true,否则返回false。
语法
setOne.equals(setTwo);
现在,让我们来看一下Java程序,比较并检查两个给定的集合是否相等。
示例1
在下面的Java程序中,我们将创建两个TreeSet类,具有相同的元素,但顺序不同。尽管如此,当我们使用equals()方法进行比较时,它将返回true,因为默认情况下TreeSet将其元素存储在排序的顺序中。
import java.util.*;
public class Example1 {
public static void main(String args[]) {
// Creating the first tree set
TreeSet<String> treeSt1 = new TreeSet<>();
// Adding elements in tree set
treeSt1.add("Tutorix");
treeSt1.add("Simply");
treeSt1.add("Easy");
treeSt1.add("Learning");
treeSt1.add("Tutorials");
treeSt1.add("Point");
System.out.println("Elements of the first set: " + treeSt1);
// Creating the second tree set
TreeSet<String> treeSt2 = new TreeSet<>();
// Adding elements in tree set
treeSt2.add("Tutorials");
treeSt2.add("Point");
treeSt2.add("Tutorix");
treeSt2.add("Simply");
treeSt2.add("Easy");
treeSt2.add("Learning");
System.out.println("Elements of the second set: " + treeSt2);
// comparing both sets
if (treeSt1.equals(treeSt2)) {
System.out.println("Both sets are equal");
} else {
System.out.println("Both sets are not equal");
}
}
}
输出
Elements of the first set: [Easy, Learning, Point, Simply, Tutorials, Tutorix]
Elements of the second set: [Easy, Learning, Point, Simply, Tutorials, Tutorix]
Both sets are equal
示例2
这是另一个Java程序,演示了如何使用equals()方法比较两个集合。我们首先初始化两个数组,然后使用asList()方法将它们转换为集合,以便我们可以使用equals()方法进行比较。
import java.util.*;
public class Example2 {
public static void main(String[] args) {
// defining the first array
String arrOne[] = { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
// creating an instance of TreeSet and storing the values of first array
TreeSet<String> trSet1 = new TreeSet<String>(Arrays.asList(arrOne));
System.out.println("Elements of the first set: " + trSet1);
// defining the second array
String arrTwo[] = { "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y" };
// creating an instance of TreeSet and storing the values of second array
TreeSet<String> trSet2 = new TreeSet<String>(Arrays.asList(arrTwo));
System.out.println("Elements of the second set: " + trSet2);
// comparing both sets
if (trSet1.equals(trSet2)) {
System.out.println("Both sets are equal");
} else {
System.out.println("Both sets are not equal");
}
}
}
输出
Elements of the first set: [P, Q, R, S, T, U, V, W, X, Y]
Elements of the second set: [P, Q, R, S, T, U, V, W, X, Y]
Both sets are equal
结论
我们从定义Java集合框架的Set接口开始本文,并在下一部分编写了两个Java程序来比较和检查两个给定的集合是否相等。为此,我们使用了TreeSet类和Set接口的equals()方法。