Java BigDecimal hashCode()方法

Java BigDecimal hashCode()方法

java.math.BigDecimal.hashCode() 返回该BigDecimal的哈希代码。对于两个数值相等而比例不同的BigDecimal对象(如4743.0和4743.00),其哈希码一般不会相同。

语法

public int hashCode()

参数: 该方法不接受任何参数。

返回值: 本方法返回一个整数,该整数等于BigDecimal对象的hashCode值。

例子

Input : BigDecimal = 67891    
Output : Hashcode : 2104621

Input : BigDecimal = 67891.000
Output : Hashcode : 2104621003

下面的程序说明了BigDecimal类的hashCode()函数:

程序1 :

// Java program to demonstrate hashCode() method
import java.io.*;
import java.math.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // Creating a BigDecimal object
        BigDecimal b;
  
        // Assigning value
        b = new BigDecimal(4743);
        System.out.print("HashCode for " + b + " is ");
        System.out.println(b.hashCode());
    }
}

输出。

HashCode for 4743 is 147033

程序2: 本程序将说明两个不同的BigDecimals的哈希码,其数值相同但比例不同,会有差异。

// Java program to demonstrate hashCode() method
import java.io.*;
import java.math.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // Creating 2 BigDecimal objects
        BigDecimal b1, b2;
  
        // Assigning values
        b1 = new BigDecimal("4743");
        b2 = new BigDecimal("4743.000");
  
        int i1, i2;
  
        i1 = b1.hashCode();
        i2 = b2.hashCode();
  
        if (i1 == i2) {
            System.out.println("HashCodes of " + 
            b1 + " and " + b2 + " are equal.");
            System.out.println("Both their HashCodes are " +
            i1 + ".");
        }
        else {
            System.out.println("HashCodes of " + b1 + " and " 
            + b2 + " are not equal.");
            System.out.println("HashCodes of " + b1 + " is " 
            + i1 + " and " + b2 + " is " + i2 + ".");
        }
    }
}

输出。

HashCodes of 4743 and 4743.000 are not equal.
HashCodes of 4743 is 147033 and 4743.000 is 147033003.

**参考资料: **https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#hashCode()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程