简体   繁体   English

Scala-使用可变HashSet时hashCode的行为等于

[英]Scala - Behaviour of hashCode & equals when using mutable HashSet

CASE#1- I have the following class: 情况#1-我有以下课程:

class Bear (val aName: String) { 
   def getName: String = aName
   override def equals (a : Any) : Boolean = { println("Test Equals"); true}      
 }

If I run the following code I get the results below: 如果运行以下代码,则会得到以下结果:

import scala.collection.mutable.HashSet 
val bear1 = new Bear("Black") 
val bear2 = new Bear("Black") 
val setBears: HashSet[Bear] = HashSet (bear1,bear2) 
println(setBears) 

res: Set(scalaproj.Bear@7d4991ad, scalaproj.Bear@28d93b30)

CASE#2- However, when I add the hashCode method to the class CASE#2-但是,当我将hashCode方法添加到类中时

class Bear (val aName: String) { 
   def getName: String = aName
   override def equals (a : Any) : Boolean = { println("Test Equals"); true}      
   override def hashCode() = { println("Test Hash");100 }
 }

and run the same code I get the results below: 并运行相同的代码,我得到以下结果:

import scala.collection.mutable.HashSet 
val bear1 = new Bear("Black") 
val bear2 = new Bear("Black") 
val setBears: HashSet[Bear] = HashSet (bear1,bear2) 
println(setBears) 

res: Test Hash
     Test Hash
     Test Equals
     Test Hash
     Set(scalaproj.Bear@64)  

My two questions: 我的两个问题:

1- CASE #2- Why is it that when the hashCode method is defined it is being called three times - twice when adding "bear1" and one time when adding "bear2" 1-案例#2-为什么在定义hashCode方法时会被调用三次-添加“ bear1”时两次,而添加“ bear2”时一次

2- CASE #1 - Why is it that the equals method is not called at all when the hashCode is not defined - eventhough it was called in CASE#2. 2-案例1-为什么在未定义hashCode的情况下根本不调用equals方法-尽管在案例2中被调用了。 (Even for a case class the overridden equals method is usually called in all cases) (即使是案例类,通常也会在所有情况下调用覆盖的equals方法)

About question #2: 关于问题2:

When two objects have the same hashCode , the equals method will be called to settle the 'tie'. 当两个对象具有相同的hashCode ,将调用equals方法来解决“领带”。 Because in this case the hash is different, equals will not be called 因为在这种情况下哈希是不同的,所以不会调用equals

About question #1: 关于问题1:

In reality what is happening is that when the HashSet is defined, the hash method for bear1 and bear2 are called, because they evaluate to the same value (namely 100), the equals will also be called. 实际上,正在发生的事情是,在定义HashSet时,将调用bear1bear2hash方法,因为它们的值equals相同的值(即100),也将调用equals

The extra call to the hashCode method is because of the println(setBears) . hashCode方法的额外调用是由于println(setBears) It shows the hash for each object in the hashset. 它显示了哈希集中每个对象的哈希。

So, when creating the HashSet, it adds up to two hashCode calls (one for each bear) and one equals call to settle the tie 因此,在创建HashSet时,它最多会添加两个hashCode调用(每个熊为一个)和一个equals调用以解决并列问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM