0

我正在XmlSlurper尝试向 Set 添加一些元素,并确保不会添加两次解析相同文本的 slurper。

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

我错过了什么吗?两个相等的对象不应该生成相同的 hashCode 吗?

同样的事情也发生在以 aXmlSlurper为键的地图上。

4

1 回答 1

0

看起来像GPathResultoverridesequals方法,但使用默认hashCodefrom Object。这就是为什么 records 和 same_records 具有不同的哈希码。

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

于 2014-01-30T22:01:00.573 回答