導讀 | Java Enum是一個非常有用的功能,但很多人通常無法充分利用,這是因為有些函式庫不會優先擇用該功能。通常我們也可以正確使用Java枚舉功能,但在許多程式庫中往往存在著這樣一個問題,於是有了這篇文章。問題很簡單:我們應該如何透過名稱或值來取得枚舉,並忽略不存在的值? |
這是我們將在範例中使用的枚舉。挑選更複雜的枚舉是為了也可以透過其他欄位展示查找枚舉。
public enum CardColor { RED, BLACK, ; } // Jackson annotation to print the enum as an Object instead of the default name. @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum CardSuit { // Unicode suits - https://en.wikipedia.org/wiki/Playing_cards_in_Unicode SPADE("Spade", String.valueOf((char) 0x2660), CardColor.BLACK), HEART("Heart", String.valueOf((char) 0x2665), CardColor.RED), DIAMOND("Diamond", String.valueOf((char) 0x2666), CardColor.RED), CLUB("Club", String.valueOf((char) 0x2663), CardColor.BLACK), ; private String displayName; private String symbol; private CardColor color; private CardSuit(String displayName, String symbol, CardColor color) { this.displayName = displayName; this.symbol = symbol; this.color = color; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public CardColor getColor() { return color; } public void setColor(CardColor color) { this.color = color; }
在 GitHub 上查看。
問題在你知道輸入有效的時候,使用Enum.valueOf非常棒。但是,如果傳入無效的名稱,那麼將會拋出例外。在某些情況下,這很好。不過,在通常情況下,我們寧願忽略異常並傳回null。
log.debug("Running valueOf"); for (String name : names) { try { log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.valueOf(name))); } catch (Exception ex) { log.warn("Exception Thrown", ex); } }
2017-02-22 14:46:38.556 [main] DEBUG c.s.examples.common.EnumLookup - Running valueOf 2017-02-22 14:46:38.804 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"} 2017-02-22 14:46:38.806 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"} 2017-02-22 14:46:38.808 [main] WARN c.s.examples.common.EnumLookup - Exception Thrown java.lang.IllegalArgumentException: No enum constant com.stubbornjava.examples.common.EnumLookup.CardSuit.Missing at java.lang.Enum.valueOf(Enum.java:238) at com.stubbornjava.examples.common.EnumLookup$CardSuit.valueOf(EnumLookup.java:1) at com.stubbornjava.examples.common.EnumLookup.main(EnumLookup.java:154)拙劣的實作
很不幸的是,以下兩種方法在程式碼庫中出現得是這麼的頻繁。反面例子,勿學。
Enum.valueOf With Try Catch(劣)這種拙劣的做法最常見於初學者。異常不應該用於控制流,並且這樣可能會有一些性能影響。不要偷懶。你必須用正確的方式去做。
/* * Please don't do this! Using try / catch for * control flow is a bad practice. */ public static CardSuit trycatchValueOf(String name) { try { return CardSuit.valueOf(name); } catch (Exception ex) { log.warn("Exception Thrown", ex); return null; } }
log.debug("Running trycatchValueOf"); for (String name : names) { log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.trycatchValueOf(name))); }
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - Running trycatchValueOf 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"} 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"} 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"} 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"} 2017-02-22 14:46:38.809 [main] WARN c.s.examples.common.EnumLookup - Exception Thrown java.lang.IllegalArgumentException: No enum constant com.stubbornjava.examples.common.EnumLookup.CardSuit.Missing at java.lang.Enum.valueOf(Enum.java:238) at com.stubbornjava.examples.common.EnumLookup$CardSuit.valueOf(EnumLookup.java:1) at com.stubbornjava.examples.common.EnumLookup$CardSuit.trycatchValueOf(EnumLookup.java:89) at com.stubbornjava.examples.common.EnumLookup.main(EnumLookup.java:171) 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null透過迭代查找(劣)
這種方法也很常見(請參閱這裡),但至少程式設計師知道不能用try/catch來捕捉異常。那麼,這種方法有什麼問題呢?沒錯,它會迭代所有枚舉,直到找到匹配的枚舉或返回null——最壞的情況下需要n次,其中n就是枚舉值的數量。有些人可能會認為這微不足道,這是過早優化了而已。但是,資料結構和演算法是CS基礎。使用Map而不是迭代集合要省力得多。這會大大提高性能嗎?不,但它是一個很好的習慣。在面試候選人時,你會對線性複雜度搜尋演算法感到滿意嗎?此時,你不應該讓這樣的程式碼審查通過。
/* * Please don't do this! It is inefficient and it's * not very hard to use Guava or a static Map as an index. */ public static CardSuit iterationFindByName(String name) { for (CardSuit suit : CardSuit.values()) { if (name.equals(suit.name())) { return suit; } } return null; }
log.debug("Running iteration"); for (String name : names) { log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.iterationFindByName(name))); }
2017-02-22 14:46:38.808 [main] DEBUG c.s.examples.common.EnumLookup - Running iteration 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"} 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"} 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"} 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"} 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null較優的實作
以下都可以透過使用Map形式的索引來運作。但是,它們之間也有一些細微的差別。
靜態Map索引(較優)用於快速查找固定大小的正確資料結構是什麼?那就是HashMap。現在透過一些額外的樣板,只要我們有很好的雜湊函數的話,我們就可以進行更有效的查找。稍微更冗長,但如果有辦法減少樣板的話,這將是極好的。
private static final Map<String, CardSuit> nameIndex = Maps.newHashMapWithExpectedSize(CardSuit.values().length); static { for (CardSuit suit : CardSuit.values()) { nameIndex.put(suit.name(), suit); } } public static CardSuit lookupByName(String name) { return nameIndex.get(name); }
log.debug("Running lookupByName"); for (String name : names) { log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.lookupByName(name))); }
2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - Running lookupByName 2017-02-22 14:46:38.809 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"} 2017-02-22 14:46:38.810 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"} 2017-02-22 14:46:38.810 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"} 2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"} 2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found nullGuava Enums.getIfPresent(推薦)
這是一個常見的用例,我們在Google的朋友為此提供了一個非常乾淨且無需樣板的解決方案。探其究竟,它甚至使用了WeakReferences和WeakHashMaps。基本上說來,這段程式碼將創建一個全域的靜態地圖,並以Enum的類別名稱鍵入,並將其用於查找。
public static CardSuit getIfPresent(String name) { return Enums.getIfPresent(CardSuit.class, name).orNull(); }
log.debug("Running Guava getIfPresent"); for (String name : names) { log.debug("looking up {} found {}", name, Json.serializer().toString(CardSuit.getIfPresent(name))); }
2017-02-22 14:46:38.813 [main] DEBUG c.s.examples.common.EnumLookup - Running Guava getIfPresent 2017-02-22 14:46:38.814 [main] DEBUG c.s.examples.common.EnumLookup - looking up SPADE found {"displayName":"Spade","symbol":"♠","color":"BLACK"} 2017-02-22 14:46:38.814 [main] DEBUG c.s.examples.common.EnumLookup - looking up HEART found {"displayName":"Heart","symbol":"♥","color":"RED"} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up DIAMOND found {"displayName":"Diamond","symbol":"♦","color":"RED"} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up CLUB found {"displayName":"Club","symbol":"♣","color":"BLACK"} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null透過欄位的進一步索引
這個完全相同的方法可以用於枚舉的其他欄位。想要透過其顯示的名稱或其他屬性來尋找枚舉並不少見。
透過欄位索引的靜態Map(較優)#與上述相同的方法,但在顯示名稱上而不是枚舉名稱上進行索引。
private static final Map<String, CardSuit> displayNameIndex = Maps.newHashMapWithExpectedSize(CardSuit.values().length); static { for (CardSuit suit : CardSuit.values()) { displayNameIndex.put(suit.getDisplayName(), suit); } } public static CardSuit lookupByDisplayName(String name) { return displayNameIndex.get(name); }
log.debug("Running lookupByDisplayName"); for (String displayName : displayNames) { log.debug("looking up {} found {}", displayName, Json.serializer().toString(CardSuit.lookupByDisplayName(displayName))); }
2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - Running lookupByDisplayName 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up Spade found {"displayName":"Spade","symbol":"♠","color":"BLACK"} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up Heart found {"displayName":"Heart","symbol":"♥","color":"RED"} 2017-02-22 14:46:38.815 [main] DEBUG c.s.examples.common.EnumLookup - looking up Diamond found {"displayName":"Diamond","symbol":"♦","color":"RED"} 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Club found {"displayName":"Club","symbol":"♣","color":"BLACK"} 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null透過欄位索引的靜態Map(較優)
#我們不能在這裡利用Guava,因為對於靜態索引建立唯一的全域金鑰將是一件困難的事。但是,這並不意味著我們沒有幫手!
public class EnumUtils { public static <T, E extends Enum<E>> Function<T, E> lookupMap(Class<E> clazz, Function<E, T> mapper) { @SuppressWarnings("unchecked") E[] emptyArray = (E[]) Array.newInstance(clazz, 0); return lookupMap(EnumSet.allOf(clazz).toArray(emptyArray), mapper); } public static <T, E extends Enum<E>> Function<T, E> lookupMap(E[] values, Function<E, T> mapper) { Map<T, E> index = Maps.newHashMapWithExpectedSize(values.length); for (E value : values) { index.put(mapper.apply(value), value); } return (T key) -> index.get(key); } }
現在我們有了一個相與樣板沒多大關聯的通用解決方案。
private static final Function<String, CardSuit> func = EnumUtils.lookupMap(CardSuit.class, e -> e.getDisplayName()); public static CardSuit lookupByDisplayNameUtil(String name) { return func.apply(name); }
log.debug("Running lookupByDisplayNameUtil"); for (String displayName : displayNames) { log.debug("looking up {} found {}", displayName, Json.serializer().toString(CardSuit.lookupByDisplayNameUtil(displayName))); }
2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - Running lookupByDisplayNameUtil 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Spade found {"displayName":"Spade","symbol":"♠","color":"BLACK"} 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Heart found {"displayName":"Heart","symbol":"♥","color":"RED"} 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Diamond found {"displayName":"Diamond","symbol":"♦","color":"RED"} 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Club found {"displayName":"Club","symbol":"♣","color":"BLACK"} 2017-02-22 14:46:38.816 [main] DEBUG c.s.examples.common.EnumLookup - looking up Missing found null結論
這裡有若干方法都可用來解決同一個問題。有些拙劣,有些比較優。
英文原文:Java Enum Lookup by Name or Field Without Throwing Exceptions
翻譯作者:碼農網 – 小峰
以上是比較不拋出異常的幾種Java枚舉查找實現的優缺點的詳細內容。更多資訊請關注PHP中文網其他相關文章!