自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

你一定需要知道的高階Java枚舉特性!

開發(fā) 開發(fā)工具
JAVA枚舉,比你想象中還要有用!我經(jīng)常發(fā)現(xiàn)自己在Java中使用枚舉來表示某個(gè)對象的一組潛在值。

[[375855]]

JAVA枚舉,比你想象中還要有用!

我經(jīng)常發(fā)現(xiàn)自己在Java中使用枚舉來表示某個(gè)對象的一組潛在值。

在編譯時(shí)確定類型可以具有什么值的能力是一種強(qiáng)大的能力,它為代碼提供了結(jié)構(gòu)和意義。

當(dāng)我第一次了解枚舉時(shí),當(dāng)時(shí)我認(rèn)為它們只是一個(gè)為常量命名的工具,可以很容易地被靜態(tài)常量字符串ENUM_VAL_NAME所取代。

后來我發(fā)現(xiàn)我錯(cuò)了。事實(shí)證明,Java枚舉具有相當(dāng)高級的特性,可以使代碼干凈、不易出錯(cuò),功能強(qiáng)大。

讓我們一起來看看Java中的一些高級枚舉特性,以及如何利用這些特性使代碼更簡單、更可讀。

枚舉是類!

在Java中,枚舉是Object的一個(gè)子類。讓我們看看所有枚舉的基類,Enum(為簡潔起見進(jìn)行了修改)。

  1. public abstract class Enum<E extends Enum<E>> 
  2.     implements Constable, Comparable<E>, Serializable { 
  3.   private final String name
  4.    
  5.   public final String name() { 
  6.       return name
  7.   } 
  8.    
  9.   private final int ordinal; 
  10.    
  11.   public final int ordinal() { 
  12.       return ordinal; 
  13.   } 
  14.    
  15.   protected Enum(String nameint ordinal) { 
  16.       this.name = name
  17.       this.ordinal = ordinal; 
  18.   } 
  19.    
  20.   public String toString() { 
  21.       return name
  22.   } 
  23.    
  24.   public final boolean equals(Object other) { 
  25.       return this==other; 
  26.   } 
  27.    
  28.   public final int hashCode() { 
  29.       return super.hashCode(); 
  30.   } 
  31.    
  32.   public final int compareTo(E o) { 
  33.       Enum<?> other = (Enum<?>)o; 
  34.       Enum<E> self = this; 
  35.       if (self.getClass() != other.getClass() && // optimization 
  36.           self.getDeclaringClass() != other.getDeclaringClass()) 
  37.           throw new ClassCastException(); 
  38.       return self.ordinal - other.ordinal; 
  39.   } 
  40.    

我們可以看到,這基本上只是一個(gè)常規(guī)的抽象類,有兩個(gè)字段,name和ordinal。

所以說枚舉都是類,所以它們具有常規(guī)類的許多特性。

我們能夠?yàn)槊杜e提供實(shí)例方法、構(gòu)造函數(shù)和字段。我們可以重寫toString(),但不能重寫hashCode()或equals(Object other)。

接下來我們看下我們的枚舉示例,Operation

  1. enum Operation { 
  2.   ADD
  3.   SUBTRACT, 
  4.   MULTIPLY 

這個(gè)枚舉表示一個(gè)Operation可以對兩個(gè)值執(zhí)行,并將生成一個(gè)結(jié)果。關(guān)于如何實(shí)現(xiàn)此功能,您最初的想法可能是使用switch語句,如下所示:

  1. public int apply(Operation operation, int arg1, int arg2) { 
  2.    switch(operation) { 
  3.      case ADD
  4.        return arg1 + arg2; 
  5.      case SUBTRACT: 
  6.        return arg1 - arg2; 
  7.      case MULTIPLY: 
  8.        return arg1 * arg2; 
  9.      default
  10.        throw new UnsupportedOperationException(); 
  11.  } 
  12.  
  13.   

當(dāng)然,這樣子會(huì)有一些問題。

第一個(gè)問題是,如果我們將一個(gè)新操作添加到我們的枚舉Operation中,編譯器不會(huì)通知我們這個(gè)開關(guān)不能正確處理新操作。

更糟糕的是,如果一個(gè)懶惰的開發(fā)人員在另一個(gè)類中復(fù)制或重新編寫這些代碼,我們可能無法更新它。

第二個(gè)問題是默認(rèn)情況default,每段程序里面都是必需的,盡管我們知道在正確的代碼里它永遠(yuǎn)不會(huì)發(fā)生。

這是因?yàn)镴ava編譯器知道上面的第一個(gè)問題,并且希望確保我們能夠處理在不知情的情況下向Operation中添加了新枚舉。

還好,Java8用函數(shù)式編程為我們提供了一個(gè)干凈的解決方案。

函數(shù)枚舉實(shí)現(xiàn)

因?yàn)槊杜e是類,所以我們可以創(chuàng)建一個(gè)枚舉字段來保存執(zhí)行操作的函數(shù)。

但是在我們找到解決方案之前,讓我們先來看看一些重構(gòu)。

首先,讓我們把開關(guān)放在enum類中。

  1.    
  2. enum Operation { 
  3.   ADD
  4.   SUBTRACT, 
  5.   MULTIPLY; 
  6.    
  7.   public static int apply(Operation operation, int arg1, int arg2) { 
  8.     switch(operation) { 
  9.       case ADD
  10.         return arg1 + arg2; 
  11.       case SUBTRACT: 
  12.         return arg1 - arg2; 
  13.       case MULTIPLY: 
  14.         return arg1 * arg2; 
  15.       default
  16.         throw new UnsupportedOperationException(); 
  17.     } 
  18.   } 
  19.    

我們可以這樣做:Operation.apply(Operation.ADD, 2, 3);

因?yàn)槲覀儸F(xiàn)在從Operation中調(diào)用方法,所以我們可以將其更改為實(shí)例方法并使用this,而不是用Operation.apply()來實(shí)現(xiàn),如下所示:

  1. public int apply(int arg1, int arg2) { 
  2.   switch(this) { 
  3.     case ADD
  4.       return arg1 + arg2; 
  5.     case SUBTRACT: 
  6.       return arg1 - arg2; 
  7.     case MULTIPLY: 
  8.       return arg1 * arg2; 
  9.     default
  10.       throw new UnsupportedOperationException(); 
  11.   } 
  12.    

像這樣使用:Operation.ADD.apply(2, 3);

看起來變好了?,F(xiàn)在讓我們更進(jìn)一步,通過使用函數(shù)式編程完全消除switch語句。

  1. enum Operation { 
  2.               ADD((x, y) -> x + y), 
  3.               SUBTRACT((x, y) -> x - y), 
  4.               MULTIPLY((x, y) -> x * y); 
  5.    
  6.               Operation(BiFunction<IntegerIntegerInteger> operation) { 
  7.                       this.operation = operation; 
  8.               } 
  9.    
  10.               private final BiFunction<IntegerIntegerInteger> operation; 
  11.    
  12.               public int apply(int x, int y) { 
  13.                       return operation.apply(x, y); 
  14.               } 
  15.    
  16.   } 
  17.    

這里我做的是:

  • 添加了一個(gè)字段 BiFunction
  • 用BiFunction創(chuàng)建了用于Operation的構(gòu)造函數(shù)。
  • 調(diào)用枚舉定義中的構(gòu)造函數(shù),并用lambda指定BiFunction

這個(gè)java.util.function.BiFunction operation字段是對采用兩個(gè)參數(shù)的函數(shù)(方法)的引用。

在我們的例子中,兩個(gè)參數(shù)都是int型,返回值也是int型。不幸的是,Java參數(shù)化類型不支持原語,所以我們必須使用Integer。

因?yàn)锽iFunction是用@functioninterface注釋的,所以我們可以使用Lambda表示法定義一個(gè)。

因?yàn)槲覀兊暮瘮?shù)接受兩個(gè)參數(shù),所以我們可以使用(x,y)來指定它們。

然后我們定義了一個(gè)單行方法,它使用 ->x+y 返回一個(gè)值。這相當(dāng)于下面的方法,只是更簡潔而已。

  1. class Adder implements BiFunction<IntegerIntegerInteger> { 
  2.         @Override 
  3.         public Integer apply(Integer x, Integer y) { 
  4.                 return x + y; 
  5.   } 

我們的新Operation實(shí)現(xiàn)采用相同的方式:Operation.ADD.apply(2, 3);.

但是,這種實(shí)現(xiàn)更好,因?yàn)榫幾g器會(huì)告訴我們何時(shí)添加了新Operation,這要求我們更新新函數(shù)。如果沒有這一點(diǎn),如果我們在添加新Operation時(shí)還不記得更新switch語句,就有可能得到UnsupportedOperationException()。

關(guān)鍵要點(diǎn)

  • Enum枚舉是Enum的擴(kuò)展類。
  • Enum枚舉可以有字段、構(gòu)造函數(shù)和實(shí)例方法。
  • Enum枚舉字段可以存儲(chǔ)函數(shù)。與lambdas配合使用,可以創(chuàng)建干凈、安全的特定于枚舉的函數(shù)實(shí)現(xiàn),并在編譯時(shí)強(qiáng)制執(zhí)行它們(而不是使用switch)。

下面是這個(gè)示例的GitHub地址。(https://github.com/alex-power/java-enum-example)

本文參考:https://medium.com/javarevisited/advanced-java-enum-features-you-need-to-know-b516a191c7e2

責(zé)任編輯:武曉燕 來源: 51CTO專欄
相關(guān)推薦

2018-08-23 16:25:29

HadoopHDFS存儲(chǔ)

2020-04-27 10:34:23

HTTPDNSDNS網(wǎng)絡(luò)協(xié)議

2024-03-21 17:29:45

2020-06-10 08:33:05

Java 編程語言開發(fā)

2020-01-03 10:11:01

數(shù)據(jù)庫安全SQL

2023-02-10 08:44:05

KafkaLinkedIn模式

2018-02-25 04:57:01

物聯(lián)網(wǎng)網(wǎng)絡(luò)技術(shù)v

2011-09-20 10:56:35

云計(jì)算PaaS

2018-09-10 09:26:33

2022-04-29 09:00:00

Platform架構(gòu)內(nèi)核線程

2022-08-10 09:03:35

TypeScript前端

2020-07-29 07:37:20

Git 修復(fù)項(xiàng)目

2015-08-06 13:30:56

商鋪線上

2022-07-06 10:07:21

物聯(lián)網(wǎng)IoT

2022-09-01 15:26:45

物聯(lián)網(wǎng)人工智能傳感器

2018-12-28 14:16:11

安全

2018-06-15 23:00:56

2022-07-15 14:58:26

數(shù)據(jù)分析人工智能IT

2017-02-09 14:46:25

Git事情

2022-04-24 09:00:00

滲透測試安全數(shù)字時(shí)代
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號