Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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

"ABC".getBytes().hashCode()

enter image description here

like image 745
tusharmath Avatar asked Feb 21 '26 14:02

tusharmath


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
like image 184
Luis Miguel Mejía Suárez Avatar answered Feb 23 '26 03:02

Luis Miguel Mejía Suárez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!