views:

48

answers:

2

What's the easiest way in Java to compare the contents of two ByteBuffers to check for equality?

A: 

oops, never mind, I forgot about the compareTo method.

Jason S
compareTo is meant for ordering, if you want to check for equality you should use equals().
Thomas Lötzer
yup, even better.
Jason S
+5  A: 

You could check the equals() method too.

Tells whether or not this buffer is equal to another object.

Two byte buffers are equal if, and only if,

  1. They have the same element type,
  2. They have the same number of remaining elements, and
  3. The two sequences of remaining elements, considered independently of their starting positions, are pointwise equal.

A byte buffer is not equal to any other type of object.

Colin Hebert
With a reputation of 17.7 k we can probably assume he has considered the `.equals` method. I suspect the OP wants to compare content only.
aioobe
@aioobe, He could be Jon Skeet, everybody is human ;)
Colin Hebert
Still, he explicitly asks for "compare the contents of two ByteBuffers".
aioobe
Of course I'm human, I forgot to check the javadoc first before asking. Duh. :-) And I asked to check for equality, so this is the best method.
Jason S