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


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


Enum 类的 hashCode() 方法返回此枚举的哈希码。

用法

public final int hashCode()

参数

NA

覆盖

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

返回值

ThehashCode() 方法返回此枚举的哈希码。

例子1

public class Enum_hashCodeMethodExample1 {
enum Seasons{
winter,summer,spring,rainy,autumn;
    }
public static void main(String[] args) {
for(Seasons seasons:Seasons.values()){
//it will print the hashCode of all the enum constants
int a =seasons.hashCode();
System.out.println("Hash code for "+seasons+" = " +a);
        }
    }
}

输出:

Hash code for winter = 248609774
Hash code for summer = 708049632
Hash code for spring = 1887400018
Hash code for rainy = 285377351
Hash code for autumn = 344560770

例子2

import java.util.EnumSet;
enum Colours{
red,green,blue,orange;
}
public class Enum_hashCodeMethodExample2 {
public static void main(String[] args) {
//printing hash codes with help of EnumSet
EnumSet.allOf(Colours.class).
forEach(Colours->System.out.println(Colours +" = "+Colours.hashCode()));

      }
    }

输出:

red = 1338823963
green = 1156060786
blue = 1612799726
orange = 1286084959

例子3

import java.lang.*;

public class Enum_hashCodeMethodExample3 {

public static void main(String[] args) {

int red1=colours.red.hashCode();

System.out.println("hash code of red ="+red1);

int Red1=colours.Red.hashCode();

System.out.println("hash code of Red ="+Red1);

int REd1=colours.REd.hashCode();

System.out.println("hash code of REd ="+REd1);

int RED1=colours.RED.hashCode();

System.out.println("hash code of RED ="+RED1);

System.out.println();

if(Integer.compare(Red1,red1)>0&&Integer.compare;(red1,REd1)>0&&Integer.compare;(red1,RED1)>0){

System.out.println(red1+" is greater.");
       }

else if(Integer.compare(Red1,RED1)>0&&Integer.compare;(red1,RED1)>0){

System.out.println(Red1+" is greater");
        }

else if(Integer.compare(REd1,RED1)>0){

System.out.println(REd1+"is greater.");
        }

else{

System.out.println("Hash code "+RED1+" is greater.");
        }
    }

enum colours{

red,Red,REd,RED;

    }
}

输出:

hash code of red =708049632
hash code of Red =1887400018
hash code of REd =285377351
hash code of RED =344560770

708049632 is greater.



相关用法


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