Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why are ByteBuffers hashCodes the same?

I have a class constructor like this:

public JavoImageCorrectedDataHeader()
    {
        ByteBuffer buffer = ByteBuffer.allocate(this.size());
        buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN);
        setByteBuffer(buffer, 0);
        System.out.println("buffer.hasCode=" + buffer.hashCode());
    }

In my other classes, I create many instances of above class in different locations and time by using

new JavoImageCorrectedDataHeader()

Then, I expected it will print out different hashCode for them. but I actually see the same hashCode is print out:

buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241
buffer.hasCode=1742602241

I must miss something about how to use the ByteBuffer.

like image 393
5YrsLaterDBA Avatar asked Jun 18 '12 19:06

5YrsLaterDBA


1 Answers

From the javadoc:

The hash code of a byte buffer depends only upon its remaining elements; that is, upon the elements from position() up to, and including, the element at limit() - 1.

Because buffer hash codes are content-dependent, it is inadvisable to use buffers as keys in hash maps or similar data structures unless it is known that their contents will not change.

If you are not populating the ByteBuffers, or are populating them with the same things, the hash codes will be identical.

like image 85
Michael Avatar answered Sep 28 '22 00:09

Michael