我正在玩一些将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吗?
对于以XmlSlurper
为键的地图,也会发生同样的事情。
答案 0 :(得分:0)
看起来GPathResult
会覆盖equals
方法,但会使用hashCode
中的默认Object
。这就是为什么记录和same_records等于不同的哈希码。
http://groovy.codehaus.org/api/groovy/util/slurpersupport/GPathResult.html