Java ByteBuffer hashCode()方法及示例
java.nio.ByteBuffer 类的 hashCode() 方法是用来返回这个缓冲区的当前哈希代码。字节缓冲区的哈希代码只取决于它的剩余元素;也就是说,取决于从position()到limit()-1的元素。因为缓冲区的哈希码是取决于内容的,所以除非知道缓冲区的内容不会改变,否则不宜使用缓冲区作为哈希图或类似数据结构的键。
语法
public int hashCode()
返回值: 该方法返回该缓冲区的当前哈希代码。下面是说明hashCode()方法的例子:
例子1 :
// Java program to demonstrate
// hashCode() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// creating object of ByteBuffer
// and allocating size capacity
ByteBuffer bb = ByteBuffer.allocate(12);
// putting the int value in the bytebuffer
bb.asIntBuffer()
.put(10)
.put(20)
.put(30);
// rewind the Bytebuffer
bb.rewind();
// print the ByteBuffer
System.out.println("Original ByteBuffer: ");
for (int i = 1; i <= 3; i++)
System.out.print(bb.getInt() + " ");
// rewind the Bytebuffer
bb.rewind();
// Reads the Int at this buffer's current position
// using hashCode() method
int value = bb.hashCode();
// print the int value
System.out.println("\n\nByte Value: " + value);
}
}
输出
Original ByteBuffer:
10 20 30
Byte Value: -219122491
例子 2 :
// Java program to demonstrate
// hashCode() method
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// creating object of ByteBuffer
// and allocating size capacity
ByteBuffer bb = ByteBuffer.allocate(12);
// Reads the Int at this buffer's current position
// using hashCode() method
int value = bb.hashCode();
// print the int value
System.out.println("Byte Value: " + value);
}
}
输出
Byte Value: -293403007
参考资料: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#hashCode-
极客教程