Uma Kalyani
Uma Kalyani

Reputation: 111

Why is the output false for the same value of 2 different hashmaps?

The code:

public static void main(String[] args) {

    HashMap<Integer, HashSet<Integer>> 
    map1 = new HashMap<Integer, HashSet<Integer>>(),
    map2 = new HashMap<Integer, HashSet<Integer>>();
    HashSet<Integer> set1=new HashSet<Integer>();
    set1.add(1);
    set1.add(2);
    map1.put(1,set1);
    map2.put(1,set1);
    System.out.println(map1.values()==map2.values());
    System.out.println(map1.values()+" "+map2.values());
}

Upvotes: 1

Views: 48

Answers (4)

== tells you whether two values are the same. However, the value of map1.values() is not a collection containing the set, but rather a reference to a collection containing a reference to the set.

Because they are references, map1.values() == map2.values() tells you whether map1.values() and map2.values() refer to the same object, which they do not, so it evaluates to false.

You can compare two objects by calling the equals method, such as with map1.values().equals(map2.values()).

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109532

Both map1 and map2 create their own lists of values. Both lists have one single element in your case, and that is the same ==. If you would have used equals then both lists would have been equal. == tests for object equality/identity.

By the way, the convention in java is:

    Map<Integer, Set<Integer>> map1 = new HashMap<>();
    Map<Integer, Set<Integer>> map2 = new HashMap<>();
    Set<Integer> set1 = new HashSet<>();

For using interfaces (Map, Set) for the variables there is reason: as such one might change the implementation, for instance to a TreeMap where the keys are sorted. Especially nice: your code will function with the broadest variation of types.

Upvotes: 0

Wojtek
Wojtek

Reputation: 1308

You are comparing the references of two Collection<HashSet<Integer>>> objects but you want to compare two <HashSet<Integer>> objects. Try extracting <HashSet<Integer>> objects from Collection<HashSet<Integer>>> objects and compare them with equals() method. By the way - result of comparing the references with == should also be true.

Upvotes: 1

Nikolas
Nikolas

Reputation: 44368

The correct comparing the equality of Object data types is to use the method equals().

map1.equals(map2);

Upvotes: 1

Related Questions