Java SortedMap equals()方法及示例
SortedMap Java中的 equals() 方法用于检查两个SortedMap实例之间是否相等。它验证作为参数传递的一个SortedMap的元素是否与这个SortedMap的元素相等。
语法
boolean equals(object obj)
参数: 该方法接受一个该地图类型的参数obj,并指的是要与该地图进行平等检查的地图。
返回值: 如果obj和地图的平等性都成立,该方法返回 true ,否则返回 false
注意 :SortedMap中的equals()方法是继承自Java中的Map接口。
下面的程序说明了equals()方法。
程序1 :
// Java code to illustrate
// the equals() method
import java.util.*;
public class Map_Demo {
public static void main(String[] args)
{
// Creating an empty SortedMap
SortedMap<Integer, String> map1
= new TreeMap<Integer, String>();
SortedMap<Integer, String> map2
= new TreeMap<Integer, String>();
// Mapping string values to int keys
map1.put(10, "Geeks");
map1.put(15, "4");
map1.put(20, "Geeks");
map1.put(25, "Welcomes");
map1.put(30, "You");
// Mapping string values to int keys
map2.put(10, "Geeks");
map2.put(15, "4");
map2.put(20, "Geeks");
map2.put(25, "Welcomes");
map2.put(30, "You");
// Displaying the Map1
System.out.println("First Map: "
+ map1);
// Displaying the Map2
System.out.println("Second Map: "
+ map2);
// Checking the equality
System.out.println(
"Equality: "
+ map1.equals(map2));
}
}
输出:
First Map:
{10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Second Map:
{10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Equality: true
程序2
// Java code to illustrate
// the equals() method
import java.util.*;
public class Map_Demo {
public static void main(String[] args)
{
// Creating an empty SortedMap
SortedMap<Integer, String> map1
= new TreeMap<Integer, String>();
SortedMap<Integer, String> map2
= new TreeMap<Integer, String>();
// Mapping string values
// to int keys for map1
map1.put(10, "Geeks");
map1.put(15, "4");
map1.put(20, "Geeks");
map1.put(25, "Welcomes");
map1.put(30, "You");
// Mapping string values
// to int keys for map2
map2.put(10, "Geeks");
map2.put(15, "4");
map2.put(20, "Geek");
map2.put(25, "Welcomes");
map2.put(30, "You");
// Displaying the map 1
System.out.println("First Map: "
+ map1);
// Displaying the map 2
System.out.println("Second Map: "
+ map2);
// Displaying the equality
System.out.println("Equality: "
+ map1.equals(map2));
}
}
输出:
First Map: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Second Map: {10=Geeks, 15=4, 20=Geek, 25=Welcomes, 30=You}
Equality: false
参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#equals(java.lang.Object)