1

Why byte[] comparison differs from hex comparison? I am computing a hash value of the same string with return type of byte[]

byte[]  hash1 = md5sum('3078RUR26')
byte[]  hash2 = md5sum('3078RUR26')

I get [B@7852e92 and [B@4e25154f respectively.

However, if I use the same function and do bitwise Integer.toHexString on hash1 and hash2 afterwards, I get 5ddff3704bc83a675f3f51671da9c2c for both statements. Why?

Omar Khazamov
  • 147
  • 1
  • 8
  • 2
    You have 2 different but equal byte arrays, i.e. the content is the same but they are stored in different places (`[B@7852e92` means it is an array of type byte with the internal object id 7852e92 - the hex part is actually the hexed hash code but the default implementation of `hashCode()` uses the internal id). – Thomas Jul 20 '16 at 12:10
  • You might want to show us how you compare the arrays but I suspect you're using `hash1 == hash2` (don't do this but use `hash1.equals( hash2 )` unless you want to know if they are the same instance). – Thomas Jul 20 '16 at 12:15

1 Answers1

1

The point is that this method md5sum most likely creates a new array each time to return its result data!

A new array means: a new reference, therefore, when you compare hash1 and hash2 using ==; or when you simply print the two references, you are told: these are two different references. Because, in the end, there are two arrays allocated in your memory.

In other words: the fact that two arrays have identical content doesn't make the array references equal!

GhostCat
  • 137,827
  • 25
  • 176
  • 248