Java Character.hashCode()方法

原文:https://www.studytonight.com/java-wrapper-class/java-character-hashcode-method

hashCode()方法是java.lang包的Character类的一部分。它用于返回给定输入的哈希代码。hashcode 被定义为与 Java 中的每个对象相关联的唯一原始整数值。

语法:

public int hashCode()

参数:

此方法中没有传递任何参数。

返回:

它返回一个与 Character 对象相关联的等效原始整数值(哈希代码)。

例 1:

这里,通过使用hashCode()方法,编译器返回一个 hashcode。

import java.lang.Character;
public class StudyTonight 
{
    public static void main(String[] args) 
    {
        Character ch1 = 'M';
        Character ch2 = 'v';

        int hv1 = ch1.hashCode(); //Returning the hash code value for the object ch1
        int hv2 = ch2.hashCode(); //Returning the hash code value for the object ch2
        System.out.println("Hash code Value : " + hv1);
        System.out.println("Hash code Value : " + hv2);
    }
}

哈希码值:77 哈希码值:118

例 2:

这里有一个用户定义的例子,任何使用这个代码的人都可以输入自己选择的值,并获得等效的哈希代码。

import java.util.Scanner;
public class StudyTonight 
{
    public static void main(String[] args) 
    {
        try 
        {
            System.out.print("Enter input: ");
            Scanner sc = new Scanner(System. in );
            Character ch = sc.next().charAt(0);
            int hv = ch.hashCode(); //Returning the hash code value for the object 
            System.out.println("Hash code Value for the given input is: " + hv);
        }
        catch(Exception e) 
        {
            System.out.println("Invalid Input!!");
        }
    }
}

输入:h 给定输入的哈希码值为:104

                                                              • *输入:T 给定输入的哈希码值为:84

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。