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


Java Boolean hashcode()用法及代码示例


Java Boolean 类的 hashCode() 方法返回 Boolean 的哈希码。

覆盖:

Boolean 类的 hashCode() 方法覆盖了 Object 类的 hashCode() 方法。

用法:

public int hashCode()
public static int hashCode(Boolean value)

参数:

NA

value- 是提供给散列的布尔值。

返回值:

此方法返回此布尔对象的哈希码值。

  • 如果对象表示为真,则返回的结果是整数 1231,
  • 如果对象表示为假,则返回的结果是整数 1237。

例子1

public class BooleanHashCodeExample1 {
    public static void main(String[] args) {
       //create two boolean objects b1 and b2
        Boolean b1 = true;
        Boolean b2 = false;
        // assign hash code of b1 and b2
        int val1 = b1.hashCode();
        int val2 = b2.hashCode();
        //print the hash code
        System.out.println("1. Hash code of true = "+val1);
        System.out.println("2. Hash code of false = "+val2);
    }
}

输出:

1. Hash code of true = 1231
2. Hash code of false = 1237

例子2

import java.util.Scanner;

public class BooleanHashCodeExample2 {
    public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your age");
        int a = scanner.nextInt();
        if(a>17) {
            System.setProperty("flag1", "true");
        }
            boolean b2 = Boolean.getBoolean("flag1");
            // calling static hash code method
            int val1 = Boolean.hashCode(b2);
            if (val1 == 1231) {
                System.out.println("Hash code match i.e. "+val1);
                System.out.println("You are an adult.\nYou are eligible to vote.");
            }
        else{
            int val2 =18-a;
            System.out.println("You are not an adult.\nYou will be eligible to vote after "+val2+" years.");
        }
    }
}

输出:

Enter your age
18
Hash code match i.e. 1231
You are an adult.
You are eligible to vote.

例子3

import java.util.Scanner;

public class BooleanHashCodeExample3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Q How many days are there in a leap year?");
        System.out.print("Ans:"); int a = scanner.nextInt();
        Boolean b1 = false;
        if(a==366){
            b1 = true;
        }
        int val1 = Boolean.hashCode(b1);
        if(val1==1231){
            System.out.println("Answer is right.");
        }
        else{
            System.out.println("Answer is wrong.");
        }
    }

输出:

Q How many days are there in a leap year?
Ans:366
Answer is right.





相关用法


注:本文由纯净天空筛选整理自 Java Boolean hashcode() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。