Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top