0

我有两组对象,我想得到两组的交集。集合中的对象如下所示

@BeanInfo
class User {

  @JsonProperty
  @BeanProperty
  var name:String = ""

  @JsonProperty
  @BeanProperty
  var id:Long = 0

  override def toString = name

  override def equals(other: Any)= other match {
      case other:User => other.id == this.id
      case _ => false
   }

}

在另一堂课中,我得到了用户集并希望看到交集。

val myFriends = friendService.getFriends("me")
val friendsFriends = friendService.getFriends("otheruser")
println(myFriends & friendsFriends) 

上面的代码不起作用并打印

Set()

但是,如果我使用 foreach 手动遍历集合,我会得到想要的结果

var matchedFriends:scala.collection.mutable.Set[User] = new HashSet[User]()    
myFriends.foreach(myFriend => {
  friendsFriends.foreach(myFriend => {
      if(myFriend == myFriend){
        matchedFriends.add(myFriend)
      }
  })
})
println(matchedFriends)

上面的代码打印

Set(Matt, Cass, Joe, Erin)

这工作得很好

val set1 = Set(1, 2, 3, 4)
val set2 = Set(4,5,6,7,1)

println(set1 & set2)

以上印刷品

Set(1, 4)

集合操作 & &- 等是否仅适用于原始对象?我是否必须对我的用户对象做一些额外的事情才能使它起作用?

4

3 回答 3

1

来自 JavaDoc:

请注意,每当重写该方法时,通常都需要重写 hashCode 方法,以维护 hashCode 方法的一般约定,即相等的对象必须具有相等的哈希码。

来自 ScalaDoc:

此外,当重写此方法时,通常需要重写 hashCode 以确保“相等”的对象(o1.equals(o2) 返回 true)哈希到相同的 Int。(o1.hashCode.equals(o2.hashCode))。

Set不工作,因为你hashCode在覆盖时坏了equals

于 2011-10-27T21:28:04.967 回答
1

我对此不是 100% 肯定,但我认为您的问题是由于在equals没有相应 custom的情况下实现了 custom 引起的hashCode。我有点惊讶您的哈希集实际上正在工作......

当然,您通过每组元素的手动循环工作正常,因为您根本不调用hashCode:)

于 2011-10-27T20:40:20.887 回答
0

覆盖时equals总是hashCode用它覆盖。

于 2011-10-27T20:36:47.627 回答