当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java BigDecimal hashCode()用法及代码示例


java.math.BigDecimal.hashCode()返回此BigDecimal的哈希码。对于具有相等值和不同精度(例如4743.0和4743.00)的两个BigDecimal对象,哈希码通常将是不同的。

用法:

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:该程序将说明具有相等值但不同比例的两个不同BigDecimal的哈希码将不同。

// 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()



相关用法


注:本文由纯净天空筛选整理自RICHIK BHATTACHARJEE大神的英文原创作品 BigDecimal hashCode() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。