Wednesday 16 April 2014

equals : Check for Maps Equality

boolean equals(Object o)
Returns true if the given object is also a map and the two maps represent the same mappings. 
 
import java.util.*;
class MapEquals{
  public static void main(String args[]){
         Map<Integer, String> myMap1 = new HashMap<> ();
  Map<Integer, String> myMap2 = new TreeMap<> ();
  Map<Integer, String> myMap3 = new TreeMap<> ();
  
  /* Put the data to myMap1 */
  myMap1.put(3, "Third");
  myMap1.put(4, "Fourth");
  myMap1.put(1, "First");
  myMap1.put(2, "Second");
  
  /* Put the data to myMap2 */
  myMap2.put(4, "Fourth");
  myMap2.put(3, "Third");
  myMap2.put(1, "First");
  myMap2.put(2, "Second");
  
  /* Put the data to myMap3 */
  myMap3.put(1, "Default");
  myMap3.put(2, "Second");
  myMap3.put(3, "Third");
  myMap3.put(4, "Fourth");
  
  System.out.println("Data in myMap1 is");
  System.out.println(myMap1);
  
  System.out.println("\nData in myMap2 is");
  System.out.println(myMap2);
  
  System.out.println("\nData in myMap3 is");
  System.out.println(myMap3);
  
  System.out.print("\nIs myMap1 and myMap2 are Equal ");
  System.out.println(myMap1.equals(myMap2));
  
  System.out.print("\nIs myMap1 and myMap3 are Equal ");
  System.out.println(myMap1.equals(myMap3));
  }
}

Output
Data in myMap1 is
{1=First, 2=Second, 3=Third, 4=Fourth}

Data in myMap2 is
{1=First, 2=Second, 3=Third, 4=Fourth}

Data in myMap3 is
{1=Default, 2=Second, 3=Third, 4=Fourth}

Is myMap1 and myMap2 are Equal true

Is myMap1 and myMap3 are Equal false



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment