Array[Byte] hashCode() returns different values every time in Scala

Viewed 225

Why does .hashCode() return different values for the same input?

"ABC".getBytes().hashCode()

enter image description here

1 Answers

It is because the hashCode of an Array doesn't depend on its values (because it is mutable) but rather it is unique for each instance, it uses its memory address. So executing the code twice creates tow different arrays that have different memory addresses that have different hash codes.

The solution is to use an immutable structure, like a List.

"ABC".getBytes().toList.hashCode()
// res: Int = 1984571950

"ABC".getBytes().toList.hashCode()
// res: Int = 1984571950
Related