Java枚舉類型重溫

在JDK1.5 以前,咱們定義常量都是: public static fianl.... 。如今好了,有了枚舉,能夠把相關的常量分組到一個枚舉類型裏,並且枚舉提供了比常量更多的方法。

一. 什麼是枚舉

枚舉是一種數據類型,具備集合的一些特色,能夠存放多個元素,但存儲對象有限且固定,枚舉也有比較常見的使用場景,如咱們須要表達性別(男、女),顏色(紅、黃、藍),星期(星期1、星期二...星期日),四季(春、夏、秋、冬),地理位置(東、西、南、北),方向(前、後、左、右)等,這些場景都很是適合枚舉。java

二. 定義枚舉

java中使用enum來定義枚舉,和classinterface具備一樣的等級,(注意是enum,而不是Enum),定義枚舉能夠有兩種狀況數組

第一種:默認構造器(空構造器)app

public enum Quarter {
SPRING, SUMMER, AUTUMN, WINTER;
}

未定義成員變量和成員方法,省略了 private Quarter() {}maven

public enum Quarter {
SPRING, SUMMER, AUTUMN, WINTER;
private Quarter(){}
}

第二種:定義了成員變量、帶參構造器ide

枚舉能夠定義成員變量,包括成員屬性、方法,抽象方法,靜態方法等測試

public enum Quarter {
SPRING("春"), SUMMER("夏"), AUTUMN("秋"), WINTER("冬");

private Quarter(String name){
this.name = name;
}
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
//靜態方法
public static void printName(){
System.out.println(Quarter.SUMMER);
}

//抽象方法
public abstract void printValue();
}

注意:枚舉和類同樣,能夠有多個構造器,即有了一個帶參構造器,還能夠有無參構造器,編譯是能夠經過的。this

除此以外:idea

  • 1.枚舉enum 默認繼承了java.lang.Enum類,實現了 java.lang.Seriablizable 和 java.lang.Comparable 兩個接口,可序列化以及進行比較;
  • 2.全部的枚舉值都是常量,默認採用了public static final 進行了修飾,enum不是類,天然也不能被繼承或實現;
  • 3.枚舉值必須在第一行,不然編譯出錯;

三. 枚舉常見用法

1.獲取枚舉元素以及成員變量

public static void main(String[] args) {
//獲取枚舉元素
System.out.println(Quarter.SPRING);
//調用toString()方法將枚舉元素轉化爲String類型
System.out.println(Quarter.SPRING.name());
System.out.println(Quarter.SPRING.toString());
//獲取成員變量
System.out.println(Quarter.SPRING.getName());
}

輸出結果:spa

SPRING  
SPRING  
SPRING  
春

2.枚舉遍歷

有時候咱們須要將枚舉元素都取出來做爲查詢條件,此時就須要進行遍歷,經過調用Quarter.values()方法.net

public static void main(String[] args) {
//經過values()方法獲得Quarter元素的數組
Quarter[] quarters = Quarter.values();
List<String> quarterParam = new ArrayList<>(quarters.length);
//將數組中的元素存儲到List集合quarterParam中
for (Quarter quarter : quarters) {
quarterParam.add(quarter.toString());
}
}

3.switch條件判斷

枚舉的元素有限且固定,經過switch作條件判斷倒是正好

public static void main(String[] args){
Quarter quarter = Quarter.AUTUMN;
switch (quarter) {
case SPRING:
System.out.println("找到了,是它:" + SPRING);
break;
case SUMMER:
System.out.println("找到了,是它:" + SUMMER);
break;
case AUTUMN:
System.out.println("找到了,是它:" + AUTUMN);
break;
case WINTER:
System.out.println("找到了,是它:" + WINTER);
break;
default:
System.out.println("未找到");
break;
}
}

執行後結果:

找到了,是它:AUTUMN
簡單說明一下:其實此處不須要default的內容,或者說將WINTER做爲default便可,由於枚舉自然有類型限制,你只能傳遞它已有的元素以及null,不過正常狀況下都會提早判斷傳遞的參數是否爲null,當switch接收到null時會報java.lang.NullPointerException。

4.枚舉比較

4.1. 判斷是否相等

枚舉判斷兩個元素是否相等直接使用==進行判斷便可,由於它非類,也沒法實例化,存儲位置天然也不會根據對象的不一樣而不一樣。

public static void main(String[] args){
System.out.println(Quarter.AUTUMN == Quarter.AUTUMN);
System.out.println(Quarter.AUTUMN == Quarter.WINTER);
}

執行結果:

true  
false

也能夠經過equals()方法進行比較,不過不必,由於其底層也是經過 == 來實現的。

public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable {
//equals比較
public final boolean equals(Object other) {
return this==other;
}
}

4.2. 順序比較

經過compareTo進行枚舉元素比較,此處比較的是在枚舉中元素的前後順序,返回的是位置序數的差值

public static void main(String[] args){
System.out.println(Quarter.AUTUMN.compareTo(Quarter.SPRING));
System.out.println(Quarter.AUTUMN.compareTo(Quarter.WINTER));
}

執行結果爲:

2  
-1

咱們看一下compareTo方法

public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable {
//元素在枚舉中的序號
private final int ordinal;
//能夠看到compareTo方法返回的就是兩個元素ordinal的差值
public final int compareTo(E o) {
Enum<?> other = (Enum<?>)o;
Enum<E> self = this;
if (self.getClass() != other.getClass() &&
self.getDeclaringClass() != other.getDeclaringClass())
throw new ClassCastException();
return self.ordinal - other.ordinal;
}
}

5.枚舉也可也實現接口

public interface WeatherInterface {
  //獲取溫度
  public String getTemperature(Quarter quarter);
}
public enum Quarter implements WeatherInterface{
SPRING("春"), SUMMER("夏"), AUTUMN("秋"), WINTER("冬");

private Quarter(String name){
this.name = name;
}

private String name;

public String getName() {
return name;
}
//重寫獲取溫度方法
@Override
public String getTemperature(Quarter quarter) {
switch (quarter) {
case SPRING:
return "適中";
case SUMMER:
return "熱";
case AUTUMN:
return "涼爽";
case WINTER:
return "寒冷";
default:
return "沒法肯定";
}
}
}

但注意枚舉不可繼承其餘類

public class Pquarter {}
//沒法編譯經過
public enum Quarter extends Pquarter {}

6.使用接口來組織枚舉

若是枚舉太多也很差管理,同時條理不夠清晰,咱們能夠經過接口來將多個相關枚舉組織在一塊兒進行管理,

public interface Weather {
enum Quarter implements Weather {
SPRING, SUMMER, AUTUMN, WINTER;
}
enum Temperature implements Weather {
MODERATE, HEAT, COOL, COLD
}
//調用時直接經過Weather.Quarter.SPRING便可。
}

四.實戰

Quarter.java 單個參數枚舉類

package cn.how2j;

/**
 * Created by kaiyiwang on 20/7/7.
 */
public enum Quarter {
  SPRING("春"), SUMMER("夏"), AUTUMN("秋"), WINTER("冬");

  private Quarter(String name){
    this.name = name;
  }

  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  //靜態方法
  public static void printName(){
    System.out.println(Quarter.SUMMER);
  }


}

兩個參數枚舉類:QuarterTwo.java

package cn.how2j;

/**
 * Created by kaiyiwang on 20/7/7.
 */
public enum QuarterTwo {
  SPRING("春", 1), SUMMER("夏", 2), AUTUMN("秋", 3), WINTER("冬", 4);

  private QuarterTwo(String name, int value){
    this.name = name;
    this.value = value;
  }

  private String name;
  private int value;

  public String getName() {
    return name;
  }

  public int getValue() {
    return value;
  }

  public void setName(String name) {
    this.name = name;
  }
  public void setValue(int value) {
    this.value = value;
  }

  //靜態方法
  public static void printName(){
    System.out.println(QuarterTwo.SUMMER);
  }


}

測試類 TestEnum.java

package cn.how2j;


/**
 * Created by kaiyiwang on 20/7/7.
 */
public class TestEnum {

  public static void main(String[] args) {
    // 獲取枚舉元素
    System.out.println(Quarter.SPRING);

    //調用toString()方法將枚舉元素轉化爲String類型
    System.out.println(Quarter.SPRING.name());
    System.out.println(Quarter.SPRING.toString());

    //獲取成員變量
    System.out.println(Quarter.SPRING.getName());

    // 多參數構建
    System.out.println("-------- TWO --------");
    System.out.println(QuarterTwo.SPRING);
    System.out.println(QuarterTwo.SPRING.name());
    System.out.println(QuarterTwo.SPRING.getName());
    System.out.println(QuarterTwo.SPRING.getValue());
    
  }

}

打印結果:

/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/bin/java -Didea.launcher.port=7534 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 15.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/lib/tools.jar:/Users/kaiyiwang/Code/java/rabbitmq_fanout/target/classes:/WEB/java/maven/repository/com/rabbitmq/amqp-client/3.6.5/amqp-client-3.6.5.jar:/WEB/java/maven/repository/cn/hutool/hutool-all/4.3.1/hutool-all-4.3.1.jar:/Applications/IntelliJ IDEA 15.app/Contents/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain cn.how2j.TestEnum
SPRING
SPRING
SPRING
春
-------- TWO --------
SPRING
SPRING
春
1

Process finished with exit code 0

其餘:

enum MallSalesOrderStatus{
    
    UNKNOW("未知", 0),
    WAIT_BUYER_PAY("等待買家支付", 10),
    WAIT_BUYER_CONFIRM_GOODS("等待買家確認收貨", 30),
    REFUND_FINISHED("退款完成", 60);
    
    private final String caption;
    private final int value;
    
    MallSalesOrderStatus(String caption, int value){
        this.caption = caption;
        this.value = value;
    }
    
}

public class Test{

  public static void main(String[] args)
  
  {
     MallSalesOrderStatus status = MallSalesOrderStatus.WAIT_BUYER_PAY;
      
      System.out.print(status);
  
  }

}

五. 總結

本文主要介紹了枚舉enum主要特色,定義,無參構造器,有參構造器,枚舉的經常使用方法舉例以及主要的應用場景。


轉載文章:
Java的枚舉enum示例詳解

相關文章
相關標籤/搜索