📜  Java中的 ByteBuffer hashCode() 方法及示例

📅  最后修改于: 2022-05-13 01:55:25.157000             🧑  作者: Mango

Java中的 ByteBuffer hashCode() 方法及示例

Java.nio.ByteBuffer类的hashCode()方法用于返回此缓冲区的当前哈希码。
字节缓冲区的哈希码仅取决于其剩余元素;也就是说,在从 position() 到且包括在 limit() – 1 处的元素的元素上。
因为缓冲区哈希码是依赖于内容的,所以不建议使用缓冲区作为哈希映射或类似数据结构中的键,除非知道它们的内容不会改变。

句法:

public int hashCode()

返回值:此方法返回此缓冲区的当前哈希码。

以下是说明 hashCode() 方法的示例:

示例 1:

// Java program to demonstrate
// getInt() 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 getInt() 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
// getInt() 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 getInt() 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–