Java中的java.util.Map.equals()方法用於檢查兩個映射之間的相等性。它驗證作為參數傳遞的一個映射的元素是否等於該映射的元素。
用法:
boolean equals(object obj)
參數:該方法接受此映射類型的一個參數obj,表示要與該映射檢查其相等性的映射。
返回值:如果兩個對象映射都相等,則該方法返回true,否則返回false。
下麵的程序演示了java.util.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 Map
Map<Integer, String> map1 = new HashMap<Integer, String>();
Map<Integer, String> map2 = new HashMap<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: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} Second Map: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} 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 Map
Map<Integer, String> map1 = new HashMap<Integer, String>();
Map<Integer, String> map2 = new HashMap<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: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} Second Map: {20=Geek, 25=Welcomes, 10=Geeks, 30=You, 15=4} Equality: false
參考: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#equals(java.lang.Object)
相關用法
- Java Set equals()用法及代碼示例
- Java Boolean equals()用法及代碼示例
- Java CopyOnWriteArrayList equals()用法及代碼示例
- Java MonthDay equals()用法及代碼示例
- Java Path equals()用法及代碼示例
- Java Long equals()用法及代碼示例
- Java NumberFormat equals()用法及代碼示例
- Java List equals()用法及代碼示例
- Java Locale equals()用法及代碼示例
- Java Instant equals()用法及代碼示例
- Java EnumMap equals()用法及代碼示例
- Java ShortBuffer equals()用法及代碼示例
- Java ValueRange equals()用法及代碼示例
- Java DoubleBuffer equals()用法及代碼示例
- Java Byte equals()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 Map equals() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。