java枚举(enum)详解(JAVA之枚举Enum)
citgpt 2024-10-22 15:35 4 浏览 0 评论
Java 枚举
知识点
概念
enum 的全称为 enumeration, 是 JDK 1.5 中引入的新特性。
在Java中,被 enum 关键字修饰的类型就是枚举类型。形式如下:
enum Color { RED, GREEN, BLUE }
如果枚举不添加任何方法,枚举值默认为从0开始的有序数值。以 Color 枚举类型举例,它的枚举常量依次为 RED:0,GREEN:1,BLUE:2。
枚举的好处:可以将常量组织起来,统一进行管理。
枚举的典型应用场景:错误码、状态机等。
枚举类型的本质
尽管 enum 看起来像是一种新的数据类型,事实上,enum是一种受限制的类,并且具有自己的方法。
创建enum时,编译器会为你生成一个相关的类,这个类继承自 java.lang.Enum。
java.lang.Enum类声明
public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable { ... }
枚举的方法
在enum中,提供了一些基本方法:
values():返回 enum 实例的数组,而且该数组中的元素严格保持在 enum 中声明时的顺序。
name():返回实例名。
ordinal():返回实例声明时的次序,从0开始。
getDeclaringClass():返回实例所属的 enum 类型。
equals() :判断是否为同一个对象。
可以使用 == 来比较enum实例。
此外,java.lang.Enum实现了Comparable和 Serializable 接口,所以也提供 compareTo() 方法。
例:展示enum的基本方法
public class EnumMethodDemo {
enum Color {RED, GREEN, BLUE;}
enum Size {BIG, MIDDLE, SMALL;}
public static void main(String args[]) {
System.out.println("=========== Print all Color ===========");
for (Color c : Color.values()) {
System.out.println(c + " ordinal: " + c.ordinal());
}
System.out.println("=========== Print all Size ===========");
for (Size s : Size.values()) {
System.out.println(s + " ordinal: " + s.ordinal());
}
Color green = Color.GREEN;
System.out.println(<span class="hljs-string">"green name(): "</span> + green.name());
System.out.println(<span class="hljs-string">"green getDeclaringClass(): "</span> + green.getDeclaringClass());
System.out.println(<span class="hljs-string">"green hashCode(): "</span> + green.hashCode());
System.out.println(<span class="hljs-string">"green compareTo Color.GREEN: "</span> + green.compareTo(Color.GREEN));
System.out.println(<span class="hljs-string">"green equals Color.GREEN: "</span> + green.equals(Color.GREEN));
System.out.println(<span class="hljs-string">"green equals Size.MIDDLE: "</span> + green.equals(Size.MIDDLE));
System.out.println(<span class="hljs-string">"green equals 1: "</span> + green.equals(<span class="hljs-number">1</span>));
System.out.format(<span class="hljs-string">"green == Color.BLUE: %b\n"</span>, green == Color.BLUE);
}
Color green = Color.GREEN;
System.out.println(<span class="hljs-string">"green name(): "</span> + green.name());
System.out.println(<span class="hljs-string">"green getDeclaringClass(): "</span> + green.getDeclaringClass());
System.out.println(<span class="hljs-string">"green hashCode(): "</span> + green.hashCode());
System.out.println(<span class="hljs-string">"green compareTo Color.GREEN: "</span> + green.compareTo(Color.GREEN));
System.out.println(<span class="hljs-string">"green equals Color.GREEN: "</span> + green.equals(Color.GREEN));
System.out.println(<span class="hljs-string">"green equals Size.MIDDLE: "</span> + green.equals(Size.MIDDLE));
System.out.println(<span class="hljs-string">"green equals 1: "</span> + green.equals(<span class="hljs-number">1</span>));
System.out.format(<span class="hljs-string">"green == Color.BLUE: %b\n"</span>, green == Color.BLUE);
}
}
输出
=========== Print all Color ===========
RED ordinal: 0
GREEN ordinal: 1
BLUE ordinal: 2
=========== Print all Size ===========
BIG ordinal: 0
MIDDLE ordinal: 1
SMALL ordinal: 2
green name(): GREEN
green getDeclaringClass(): class org.zp.javase.enumeration.EnumDemo$Color
green hashCode(): 460141958
green compareTo Color.GREEN: 0
green equals Color.GREEN: true
green equals Size.MIDDLE: false
green equals 1: false
green == Color.BLUE: false
枚举的特性
枚举的特性,归结起来就是一句话:
除了不能继承,基本上可以将 enum 看做一个常规的类。
但是这句话需要拆分去理解,让我们细细道来。
枚举可以添加方法
在概念章节提到了,枚举值默认为从0开始的有序数值 。那么问题来了:如何为枚举显示的赋值。
Java 不允许使用 = 为枚举常量赋值
如果你接触过C/C++,你肯定会很自然的想到赋值符号 = 。在C/C++语言中的enum,可以用赋值符号=显示的为枚举常量赋值;但是 ,很遗憾,Java 语法中却不允许使用赋值符号 = 为枚举常量赋值。
例:C/C++ 语言中的枚举声明
typedef enum{
ONE = 1,
TWO,
THREE = 3,
TEN = 10
} Number;
枚举可以添加普通方法、静态方法、抽象方法、构造方法
Java 虽然不能直接为实例赋值,但是它有更优秀的解决方案:为 enum 添加方法来间接实现显示赋值。
创建 enum 时,可以为其添加多种方法,甚至可以为其添加构造方法。
注意一个细节:如果要为enum定义方法,那么必须在enum的最后一个实例尾部添加一个分号。此外,在enum中,必须先定义实例,不能将字段或方法定义在实例前面。否则,编译器会报错。
例:全面展示如何在枚举中定义普通方法、静态方法、抽象方法、构造方法
public enum ErrorCode {
OK(0) {
public String getDescription() {
return "成功";
}
},
ERROR_A(100) {
public String getDescription() {
return "错误A";
}
},
ERROR_B(200) {
public String getDescription() {
return "错误B";
}
};
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-comment">// 构造方法:enum的构造方法只能被声明为private权限或不声明权限</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">ErrorCode</span><span class="hljs-params">(<span class="hljs-keyword">int</span> number)</span> </span>{ <span class="hljs-comment">// 构造方法</span>
<span class="hljs-keyword">this</span>.code = number;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// 普通方法</span>
<span class="hljs-keyword">return</span> code;
} <span class="hljs-comment">// 普通方法</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>; <span class="hljs-comment">// 抽象方法</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> </span>{ <span class="hljs-comment">// 静态方法</span>
<span class="hljs-keyword">for</span> (ErrorCode s : ErrorCode.values()) {
System.out.println(<span class="hljs-string">"code: "</span> + s.getCode() + <span class="hljs-string">", description: "</span> + s.getDescription());
}
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-comment">// 构造方法:enum的构造方法只能被声明为private权限或不声明权限</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">ErrorCode</span><span class="hljs-params">(<span class="hljs-keyword">int</span> number)</span> </span>{ <span class="hljs-comment">// 构造方法</span>
<span class="hljs-keyword">this</span>.code = number;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// 普通方法</span>
<span class="hljs-keyword">return</span> code;
} <span class="hljs-comment">// 普通方法</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>; <span class="hljs-comment">// 抽象方法</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> </span>{ <span class="hljs-comment">// 静态方法</span>
<span class="hljs-keyword">for</span> (ErrorCode s : ErrorCode.values()) {
System.out.println(<span class="hljs-string">"code: "</span> + s.getCode() + <span class="hljs-string">", description: "</span> + s.getDescription());
}
}
}
注:上面的例子并不可取,仅仅是为了展示枚举支持定义各种方法。下面是一个简化的例子
例:一个错误码枚举类型的定义
本例和上例的执行结果完全相同。
public enum ErrorCodeEn {
OK(0, "成功"),
ERROR_A(100, "错误A"),
ERROR_B(200, "错误B");
ErrorCodeEn(<span class="hljs-keyword">int</span> number, String description) {
<span class="hljs-keyword">this</span>.code = number;
<span class="hljs-keyword">this</span>.description = description;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-keyword">private</span> String description;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> code;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> description;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> </span>{ <span class="hljs-comment">// 静态方法</span>
<span class="hljs-keyword">for</span> (ErrorCodeEn s : ErrorCodeEn.values()) {
System.out.println(<span class="hljs-string">"code: "</span> + s.getCode() + <span class="hljs-string">", description: "</span> + s.getDescription());
}
}
ErrorCodeEn(<span class="hljs-keyword">int</span> number, String description) {
<span class="hljs-keyword">this</span>.code = number;
<span class="hljs-keyword">this</span>.description = description;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-keyword">private</span> String description;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> code;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> description;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> </span>{ <span class="hljs-comment">// 静态方法</span>
<span class="hljs-keyword">for</span> (ErrorCodeEn s : ErrorCodeEn.values()) {
System.out.println(<span class="hljs-string">"code: "</span> + s.getCode() + <span class="hljs-string">", description: "</span> + s.getDescription());
}
}
}
枚举可以实现接口
enum 可以像一般类一样实现接口。
同样是实现上一节中的错误码枚举类,通过实现接口,可以约束它的方法。
public interface INumberEnum {
int getCode();
String getDescription();
}
public enum ErrorCodeEn2 implements INumberEnum {
OK(0, "成功"),
ERROR_A(100, "错误A"),
ERROR_B(200, "错误B");
ErrorCodeEn2(<span class="hljs-keyword">int</span> number, String description) {
<span class="hljs-keyword">this</span>.code = number;
<span class="hljs-keyword">this</span>.description = description;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-keyword">private</span> String description;
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> code;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> description;
}
ErrorCodeEn2(<span class="hljs-keyword">int</span> number, String description) {
<span class="hljs-keyword">this</span>.code = number;
<span class="hljs-keyword">this</span>.description = description;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-keyword">private</span> String description;
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> code;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> description;
}
}
枚举不可以继承
enum 不可以继承另外一个类,当然,也不能继承另一个 enum 。
因为 enum 实际上都继承自 java.lang.Enum 类,而 Java 不支持多重继承,所以 enum 不能再继承其他类,当然也不能继承另一个 enum。
枚举的应用场景
组织常量
在JDK1.5 之前,在Java中定义常量都是public static final TYPE a; 这样的形式。有了枚举,你可以将有关联关系的常量组织起来,使代码更加易读、安全,并且还可以使用枚举提供的方法。
枚举声明的格式
注:如果枚举中没有定义方法,也可以在最后一个实例后面加逗号、分号或什么都不加。
下面三种声明方式是等价的:
enum Color { RED, GREEN, BLUE }
enum Color { RED, GREEN, BLUE, }
enum Color { RED, GREEN, BLUE; }
switch 状态机
我们经常使用switch语句来写状态机。JDK7以后,switch已经支持 int、char、String、enum 类型的参数。这几种类型的参数比较起来,使用枚举的switch代码更具有可读性。
enum Signal {RED, YELLOW, GREEN}
public static String getTrafficInstruct(Signal signal) {
String instruct = "信号灯故障";
switch (signal) {
case RED:
instruct = "红灯停";
break;
case YELLOW:
instruct = "黄灯请注意";
break;
case GREEN:
instruct = "绿灯行";
break;
default:
break;
}
return instruct;
}
组织枚举
可以将类型相近的枚举通过接口或类组织起来。
但是一般用接口方式进行组织。
原因是:Java接口在编译时会自动为enum类型加上public static修饰符;Java类在编译时会自动为 enum 类型加上static修饰符。看出差异了吗?没错,就是说,在类中组织 enum,如果你不给它修饰为 public,那么只能在本包中进行访问。
例:在接口中组织 enum
public interface Plant {
enum Vegetable implements INumberEnum {
POTATO(0, "土豆"),
TOMATO(0, "西红柿");
Vegetable(<span class="hljs-keyword">int</span> number, String description) {
<span class="hljs-keyword">this</span>.code = number;
<span class="hljs-keyword">this</span>.description = description;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-keyword">private</span> String description;
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
}
}
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Fruit</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">INumberEnum</span> </span>{
APPLE(<span class="hljs-number">0</span>, <span class="hljs-string">"苹果"</span>),
ORANGE(<span class="hljs-number">0</span>, <span class="hljs-string">"桔子"</span>),
BANANA(<span class="hljs-number">0</span>, <span class="hljs-string">"香蕉"</span>);
Fruit(<span class="hljs-keyword">int</span> number, String description) {
<span class="hljs-keyword">this</span>.code = number;
<span class="hljs-keyword">this</span>.description = description;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-keyword">private</span> String description;
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
}
}
Vegetable(<span class="hljs-keyword">int</span> number, String description) {
<span class="hljs-keyword">this</span>.code = number;
<span class="hljs-keyword">this</span>.description = description;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-keyword">private</span> String description;
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
}
}
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Fruit</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">INumberEnum</span> </span>{
APPLE(<span class="hljs-number">0</span>, <span class="hljs-string">"苹果"</span>),
ORANGE(<span class="hljs-number">0</span>, <span class="hljs-string">"桔子"</span>),
BANANA(<span class="hljs-number">0</span>, <span class="hljs-string">"香蕉"</span>);
Fruit(<span class="hljs-keyword">int</span> number, String description) {
<span class="hljs-keyword">this</span>.code = number;
<span class="hljs-keyword">this</span>.description = description;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> code;
<span class="hljs-keyword">private</span> String description;
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCode</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
}
}
}
例:在类中组织 enum
本例和上例效果相同。
public class Plant2 {
public enum Vegetable implements INumberEnum {...} // 省略代码
public enum Fruit implements INumberEnum {...} // 省略代码
}
策略枚举
EffectiveJava中展示了一种策略枚举。这种枚举通过枚举嵌套枚举的方式,将枚举常量分类处理。
这种做法虽然没有switch语句简洁,但是更加安全、灵活。
例:EffectvieJava中的策略枚举范例
enum PayrollDay {
MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY(
PayType.WEEKDAY), THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY), SATURDAY(
PayType.WEEKEND), SUNDAY(PayType.WEEKEND);
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> PayType payType;
PayrollDay(PayType payType) {
<span class="hljs-keyword">this</span>.payType = payType;
}
<span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">pay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hoursWorked, <span class="hljs-keyword">double</span> payRate)</span> </span>{
<span class="hljs-keyword">return</span> payType.pay(hoursWorked, payRate);
}
<span class="hljs-comment">// 策略枚举</span>
<span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">PayType</span> </span>{
WEEKDAY {
<span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">overtimePay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hours, <span class="hljs-keyword">double</span> payRate)</span> </span>{
<span class="hljs-keyword">return</span> hours <= HOURS_PER_SHIFT ? <span class="hljs-number">0</span> : (hours - HOURS_PER_SHIFT)
* payRate / <span class="hljs-number">2</span>;
}
},
WEEKEND {
<span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">overtimePay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hours, <span class="hljs-keyword">double</span> payRate)</span> </span>{
<span class="hljs-keyword">return</span> hours * payRate / <span class="hljs-number">2</span>;
}
};
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> HOURS_PER_SHIFT = <span class="hljs-number">8</span>;
<span class="hljs-function"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">double</span> <span class="hljs-title">overtimePay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hrs, <span class="hljs-keyword">double</span> payRate)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">pay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hoursWorked, <span class="hljs-keyword">double</span> payRate)</span> </span>{
<span class="hljs-keyword">double</span> basePay = hoursWorked * payRate;
<span class="hljs-keyword">return</span> basePay + overtimePay(hoursWorked, payRate);
}
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> PayType payType;
PayrollDay(PayType payType) {
<span class="hljs-keyword">this</span>.payType = payType;
}
<span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">pay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hoursWorked, <span class="hljs-keyword">double</span> payRate)</span> </span>{
<span class="hljs-keyword">return</span> payType.pay(hoursWorked, payRate);
}
<span class="hljs-comment">// 策略枚举</span>
<span class="hljs-keyword">private</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">PayType</span> </span>{
WEEKDAY {
<span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">overtimePay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hours, <span class="hljs-keyword">double</span> payRate)</span> </span>{
<span class="hljs-keyword">return</span> hours <= HOURS_PER_SHIFT ? <span class="hljs-number">0</span> : (hours - HOURS_PER_SHIFT)
* payRate / <span class="hljs-number">2</span>;
}
},
WEEKEND {
<span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">overtimePay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hours, <span class="hljs-keyword">double</span> payRate)</span> </span>{
<span class="hljs-keyword">return</span> hours * payRate / <span class="hljs-number">2</span>;
}
};
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> HOURS_PER_SHIFT = <span class="hljs-number">8</span>;
<span class="hljs-function"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">double</span> <span class="hljs-title">overtimePay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hrs, <span class="hljs-keyword">double</span> payRate)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">pay</span><span class="hljs-params">(<span class="hljs-keyword">double</span> hoursWorked, <span class="hljs-keyword">double</span> payRate)</span> </span>{
<span class="hljs-keyword">double</span> basePay = hoursWorked * payRate;
<span class="hljs-keyword">return</span> basePay + overtimePay(hoursWorked, payRate);
}
}
}
测试
System.out.println("时薪100的人在周五工作8小时的收入:" + PayrollDay.FRIDAY.pay(8.0, 100));
System.out.println("时薪100的人在周六工作8小时的收入:" + PayrollDay.SATURDAY.pay(8.0, 100));
EnumSet和EnumMap
Java 中提供了两个方便操作enum的工具类——EnumSet 和 EnumMap。
EnumSet 是枚举类型的高性能 Set 实现。它要求放入它的枚举常量必须属于同一枚举类型。
EnumMap 是专门为枚举类型量身定做的 Map 实现。虽然使用其它的 Map 实现(如HashMap)也能完成枚举类型实例到值得映射,但是使用 EnumMap 会更加高效:它只能接收同一枚举类型的实例作为键值,并且由于枚举类型实例的数量相对固定并且有限,所以 EnumMap 使用数组来存放与枚举类型对应的值。这使得 EnumMap 的效率非常高。
// EnumSet的使用
System.out.println("EnumSet展示");
EnumSet<ErrorCodeEn> errSet = EnumSet.allOf(ErrorCodeEn.class);
for (ErrorCodeEn e : errSet) {
System.out.println(e.name() + " : " + e.ordinal());
}
// EnumMap的使用
System.out.println("EnumMap展示");
EnumMap<StateMachine.Signal, String> errMap = new EnumMap(StateMachine.Signal.class);
errMap.put(StateMachine.Signal.RED, "红灯");
errMap.put(StateMachine.Signal.YELLOW, "黄灯");
errMap.put(StateMachine.Signal.GREEN, "绿灯");
for (Iterator<Map.Entry<StateMachine.Signal, String>> iter = errMap.entrySet().iterator(); iter.hasNext()😉 {
Map.Entry<StateMachine.Signal, String> entry = iter.next();
System.out.println(entry.getKey().name() + " : " + entry.getValue());
}
相关推荐
- js中arguments详解
-
一、简介了解arguments这个对象之前先来认识一下javascript的一些功能:其实Javascript并没有重载函数的功能,但是Arguments对象能够模拟重载。Javascrip中每个函数...
- firewall-cmd 常用命令
-
目录firewalldzone说明firewallzone内容说明firewall-cmd常用参数firewall-cmd常用命令常用命令 回到顶部firewalldzone...
- epel-release 是什么
-
EPEL-release(ExtraPackagesforEnterpriseLinux)是一个软件仓库,它为企业级Linux发行版(如CentOS、RHEL等)提供额外的软件包。以下是关于E...
- FullGC详解 什么是 JVM 的 GC
-
前言:背景:一、什么是JVM的GC?JVM(JavaVirtualMachine)。JVM是Java程序的虚拟机,是一种实现Java语言的解...
-
2024-10-26 08:50 citgpt
- 跨域(CrossOrigin)
-
1.介绍 1)跨域问题:跨域问题是在网络中,当一个网络的运行脚本(通常时JavaScript)试图访问另一个网络的资源时,如果这两个网络的端口、协议和域名不一致时就会出现跨域问题。 通俗讲...
- 微服务架构和分布式架构的区别
-
1、含义不同微服务架构:微服务架构风格是一种将一个单一应用程序开发为一组小型服务的方法,每个服务运行在自己的进程中,服务间通信采用轻量级通信机制(通常用HTTP资源API)。这些服务围绕业务能力构建并...
- 深入理解与应用CSS clip-path 属性
-
clip-pathclip-path是什么clip-path 是一个CSS属性,允许开发者创建一个剪切区域,从而决定元素的哪些部分可见,哪些部分会被隐...
-
2024-10-25 11:51 citgpt
- Request.ServerVariables 大全
-
Request.ServerVariables("Url")返回服务器地址Request.ServerVariables("Path_Info")客户端提供的路...
- python操作Kafka
-
目录一、python操作kafka1.python使用kafka生产者2.python使用kafka消费者3.使用docker中的kafka二、python操作kafka细...
- Runtime.getRuntime().exec详解
-
Runtime.getRuntime().exec详解概述Runtime.getRuntime().exec用于调用外部可执行程序或系统命令,并重定向外部程序的标准输入、标准输出和标准错误到缓冲池。...
- promise.all详解 promise.all是干什么的
-
promise.all详解promise.all中所有的请求成功了,走.then(),在.then()中能得到一个数组,数组中是每个请求resolve抛出的结果...
-
2024-10-24 16:21 citgpt
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- oracleclient (56)
- springbatch (59)
- oracle恢复数据 (56)
- 简单工厂模式 (68)
- 函数指针 (72)
- fill_parent (135)
- java配置环境变量 (140)
- linux文件系统 (56)
- 计算机操作系统教程 (60)
- 静态ip (63)
- notifyicon (55)
- 线程同步 (58)
- xcode 4 5 (60)
- 调试器 (60)
- c0000005 (63)
- html代码大全 (61)
- header utf 8 (61)
- 多线程多进程 (65)
- require_once (60)
- 百度网盘下载速度慢破解方法 (72)
- 谷歌浏览器免费入口 (72)
- npm list (64)
- 网站打开速度检测 (59)
- 网站建设流程图 (58)
- this关键字 (67)