0

Why do I need the extra step to make it intValue in order for them to equal?

Is it because it is comparing if it is the same object?

        Map<Integer, Integer> m1 = new HashMap<Integer,Integer>();
        Map<Integer, Integer> m2 = new HashMap<Integer,Integer>();

        m1.put(1, 1000);
        m2.put(2, 1000);

        for (Map.Entry<Integer,Integer> mmm : m1.entrySet()) {
            if (mmm.getValue() == m2.get(2)) {
                 System.out.println("I should be equal");
            }
            if (mmm.getValue().intValue() == m2.get(2).intValue()) {
                 System.out.println("but im equal");
            }
        }
Airborne STD
  • 47
  • 1
  • 7
  • What does `Integer i1 = 1000; Integer i2 = 1000; System.out.println("eq: " + (i1 == i2))` give? Why might that be the case? [This question on comparing Integers](https://stackoverflow.com/questions/1514910/how-to-properly-compare-two-integers-in-java) gives some hints. – KevinO May 04 '21 at 04:24

1 Answers1

2

Yes, the statement

mmm.getValue() == m2.get(2)

checks whether both refer to the same object, not the values within them. To compare values something like this can also be done:

Map<Integer, Integer> m1 = new HashMap<Integer,Integer>();
    Map<Integer, Integer> m2 = new HashMap<Integer,Integer>();

    m1.put(1, 1000);
    m2.put(2, 1000);

    for (Map.Entry<Integer,Integer> mmm : m1.entrySet()) {
        if (mmm.getValue().compareTo(m2.get(2)) == 0) {
             System.out.println("I should be equal");
        }
        if (mmm.getValue().intValue() == m2.get(2).intValue()) {
             System.out.println("but im equal");
        }
    }
Charchit Kapoor
  • 8,934
  • 2
  • 8
  • 24
  • 2
    If you just want to test for equality `equals` will probably be faster than `compareTo`. And definitely simpler and more readable. – Stephen C May 04 '21 at 05:01