Java.lang.Eunm 类用法

本文通过一个Java示例展示了如何使用枚举类型的各种方法,包括比较、获取声明类、获取名称、获取序号、根据字符串获取枚举值以及获取所有枚举值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package enumeration;

 

public class TestEnum {

public enum Jobs { ENGINEER,PROGRAMMER,SALES};

public enum NewDepartment {ENGINEER, MARKETING, SALES, HR};

public static void main(String[] args)

{

 //compareTo

 int i = NewDepartment.MARKETING.compareTo(NewDepartment.SALES);

 int i2 = NewDepartment.MARKETING.compareTo(NewDepartment.ENGINEER);

 int i3 = NewDepartment.MARKETING.compareTo(NewDepartment.MARKETING);

 System.out.printf("NewDepartment.MARKETING compare to NewDepartment.SALES is %d\n", i);

 System.out.printf("NewDepartment.MARKETING compare to NewDepartment.ENGINEER is %d\n", i2);

 System.out.printf("NewDepartment.MARKETING compare to NewDepartment.MARKETING is %d\n", i3);

 //equals

 boolean b = NewDepartment.HR.equals(NewDepartment.SALES);

 boolean b2 = NewDepartment.HR.equals(NewDepartment.HR);

 System.out.printf("HR and NewDepartment.SALES are equal? %b\n", b);

 System.out.printf("HR and HR are equal? %b\n", b2);

 

 //getDeclaringClass

 Class c = NewDepartment.ENGINEER.getDeclaringClass();

 Class c2 = Jobs.ENGINEER.getDeclaringClass();

 System.out.printf("NewDepartment.ENGINEER\'s declaring class is %s\n", c.getName());

 System.out.printf("ENGINEER\'s declaring is %s\n", c2.getName());

 

 //name

 String s = NewDepartment.ENGINEER.name();

 String s2 = NewDepartment.ENGINEER.toString();

 System.out.printf("s and s2 are equals? %b\n", s.equals(s2));

 

 //ordinal

 int j = NewDepartment.ENGINEER.ordinal();

 int j2 = NewDepartment.HR.ordinal();

 System.out.printf("NewDepartment.ENGINEER\'s ordinal is %d\n", j);

 System.out.printf("NewDepartment.HR\'s ordinal is %d\n", j2);

 

 //valueOf

 NewDepartment dept = NewDepartment.valueOf("HR");

 boolean b3 = dept.equals(NewDepartment.HR);

 System.out.printf("dept(%s) is HR? %b\n", dept.name(), b3);

 

 //values

 NewDepartment[] depts = NewDepartment.values();

 System.out.printf("NewDepartment type has %d values, there are %s, %s, %s and %s.\n",

     depts.length, depts[0].name(), depts[1].name(), depts[2].name(), depts[3].name());

 

}

 

}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值