0

I was playing around with adding some XmlSlurper elements to a Set and making sure a slurper that parsed the same text as another wouldn't be added twice.

def CAR_RECORDS = '''
    <records>
      <car name='HSV Maloo' make='Holden' year='2006'>
        <country>Australia</country>
        <record type='speed'>
          Production Pickup Truck with speed of 271kph
        </record>
      </car>
      <car name='P50' make='Peel' year='1962'>
        <country>Isle of Man</country>
        <record type='size'>
          Smallest Street-Legal Car at 99cm wide and 59 kg in weight
        </record>
      </car>
      <car name='Royale' make='Bugatti' year='1931'>
        <country>France</country>
        <record type='price'>Most Valuable Car at $15 million</record>
      </car>
    </records>
    '''

def records = new XmlSlurper().parseText(CAR_RECORDS)
def same_records = new XmlSlurper().parseText(CAR_RECORDS)

// obviously equal
assert records == same_records

def slurpers = new HashSet()
slurpers.add(records)
slurpers.add(same_records)

//why are there 2 entries here?
assert slurpers.size() == 1

Am I missing something? Shouldn't two objects that are equal generate the same hashCode?

Same thing happens for a map with an XmlSlurper as a key.

bdkosher
  • 5,753
  • 2
  • 33
  • 40
jacobono
  • 3
  • 1
  • You expect it to scan the entire XML parse tree to generate a hash code? I'm surprised the equality comparison returns true tbh – tim_yates Jan 30 '14 at 19:37
  • well, when you put it like that, heh. My first thought when I tried this was that equality wouldn't work, but when it did, I thought it _must_ do something. – jacobono Jan 30 '14 at 21:35

1 Answers1

0

Looks like GPathResult overrides equals method but use default hashCode from Object. Thats why records and same_records are equals with different hashcodes.

http://groovy.codehaus.org/api/groovy/util/slurpersupport/GPathResult.html

Normal
  • 1,347
  • 4
  • 17
  • 34
  • Yeah, equals just compares the text https://github.com/groovy/groovy-core/blob/master/subprojects/groovy-xml/src/main/java/groovy/util/slurpersupport/GPathResult.java#L370 – tim_yates Jan 30 '14 at 22:04
  • Adding public int hashCode() { return getText().hashCode() } to XmlSlurper should work – Michael Rutherfurd Jan 30 '14 at 22:42