Roman Funk
Roman Funk

Reputation: 35

Why is `java.util.LinkedHashMap` not equal when key and value are identical?

I have a linkedHashMap with just one element and I want to compare it for equality. So I wrote the following spock test case:

    def "Get average value for a date key"() {
    given:
    def ex = ["08-2018": 13 as BigDecimal] as Map<String, Integer>

    when:
    def wta = new worktime_average()
    def result = wta.get_time_vals(wtime, '08-2018') as Map<String, Integer>

    then:
    result.values()[0] == ex.values()[0] // Pass!
    result.keySet() == ex.keySet() // Pass!
    result == ex // Failed!!
    }

It fails saying:

result == ex
|      |  |
|      |  [08-2018:13] (java.util.LinkedHashMap)
|      false
[08-2018:13] (java.util.LinkedHashMap)

I have no clue why. Any guesses?

Upvotes: 3

Views: 1362

Answers (1)

cjstehno
cjstehno

Reputation: 13994

In Groovy, a String (single-quote) is not equivalent to a GString (double-quote) - this often pops up when they are used as Map keys. Ensure that your keys are Strings by calling as String or .toString() before setting/using the key.

Upvotes: 1

Related Questions