📜  如何比较Java中的两个 TreeMap 对象?

📅  最后修改于: 2022-05-13 01:54:26.474000             🧑  作者: Mango

如何比较Java中的两个 TreeMap 对象?

Java中的TreeMap类提供了一种按排序顺序存储键值对的方法。下面的示例显示了如何使用equals()比较两个 TreeMap 对象 方法。它比较两个 TreeMap 对象,如果两个映射具有相同的映射,则返回 true,否则返回 false。

句法:

boolean equals(Object o)

返回:如果两个映射相等则返回真,否则返回假。

Java
// Java program to Compare Two TreeMap Objects
import java.io.*;
import java.util.ArrayList;
import java.util.TreeMap;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Creating first TreeMap
        TreeMap Office1
            = new TreeMap();
 
        Office1.put(1, "Mumbai");
        Office1.put(2, "Delhi");
 
        // Creating second TreeMap
        TreeMap Office2
            = new TreeMap();
 
        Office2.put(1, "Mumbai");
        Office2.put(2, "Delhi");
 
        // equals compares two TreeMap objects and
        // returns true if both of the maps have the same
        // mappings.
        System.out.println(Office1.equals(Office2));
 
        // add new mapping to second TreeMap
        Office2.put(3, "Goa");
 
        // this will return false as both TreeMap objects do
        // not contain same mappings
        System.out.println(Office1.equals(Office2));
    }
}


输出
true
false