tags:

views:

480

answers:

4

If I have two byte[] arrays, is there a built-in function to compare them ala C's memcmp() ?

+4  A: 

There's Arrays.equals().

I don't know whether the JVM implementation actually optimizes this if a corresponding instruction exists in the hardware, but I doubt it.

Also, if I remember my C correctly, strcmp works up to a null terminator (making it useful for C strings), The Arrays version will compare the entire array since Java programmers rarely bother with null-terminated arrays. You could easily write your own function, though, if you care about the null-terminator.

Uri
I'm curious for a case where someone would null terminate their own array in Java
matt b
I never tried that, but I would assume that maybe if one invoked a native method in C and used a buffer...
Uri
Where did strcmp come from? The question was about memcmp, and I can't see strcmp in edit histories either.
laalto
+1  A: 

[Arrays.equals][1]

[1]: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#equals(byte[], byte[])

oykuo
A: 

what about the equivalent for same in c#?

Learner
Probably better to ask as a separate question or search SO for an existing answer...
Peter
+2  A: 

The java.util.Arrays.equals(byte[], byte[]) method is your friend.

lavinio