简体   繁体   中英

How can I generate hash codes with Scala

I want to generate a non cryptographic hash code for a string in Scala 2.11

I looked online and found a class called MurmurHash3 but when I try to use it I get a very unhelpful class MurmurHash3 in package hashing cannot be accessed in package scala.util.hashing

Why would I not be able to access the package? Is there an alternative?

the class MurmurHash3 is private

private[hashing] class MurmurHash3

what you need, is a companion object MurmurHash3. Don't try to instantiate it. Just use it's methods, like in a static class

util.hashing.MurmurHash3.stringHash("")

public instace of MurmurHash3 is object not a class :

Welcome to Scala version 2.11.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_65)
Type in expressions to have them evaluated.
Type :help for more information.

scala> scala.util.hashing.MurmurHash3.arrayHash(Array(10,20,30))
res0: Int = -864874452

You can try java's security.MessageDigest to generate hash code in scala. It will generate same hash code for same input string. I used this in Scala 2.11.x

import java.security.MessageDigest

def getMD5Hash(fileName: String): String = {
    val msgDigest:MessageDigest = MessageDigest.getInstance("MD5")
    val MD5Hash = msgDigest.digest(fileName.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft("") {_ + _}
    MD5Hash
}

Hope it Helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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