Using Alternative Comparison in a HashSet

I came across this problem when creating a HashSet [Array [Byte]] for use as HatTrie.

Apparently, the standard equals () method on arrays checks for identity. How can I provide a HashSet with an alternative Comparator that uses .deepEquals () to check if an element is contained in a set?

Basically, I want this test to pass:

describe ("A HashSet of Byte Array") {      

    it("must contain arrays that are equivalent to one that has been added") {
        val set = new HashSet[Array[Byte]]()
        set += "ab".getBytes("UTF-8")
        set must contain ("ab".getBytes("UTF-8"))           
    }
}

I cannot legally wrap the [Byte] array in another object, because there are a lot of them. Other than writing a new HashSet implementation for this purpose, is there anything I can do?

+3
source share
1 answer

, , , -. , , , , - , .

, , -. , , . , 0, node.

HashSet, . -, . .

, . - , , , , - .

, . , .

, HashSet, equals. , HashSet , , .

- equals "==", deepEquals, Pimp My Class, HashSet.

Edit

HashSet, . , HashSet, contains. :

class MyHashSet[A] extends scala.collection.mutable.HashSet[A] {
  override def contains(elem: A): Boolean = elem match {
    case arr : Array[_] => this.elements exists (arr deepEquals _)
    case _ => super.contains(elem)
  }
}

, . , REPL, , , . , - , , - .: -)

+1

Source: https://habr.com/ru/post/1713690/


All Articles