Thinking in Java——筆記(19)

来源:http://www.cnblogs.com/apolloqq/archive/2016/12/26/6223772.html
-Advertisement-
Play Games

Enumerated Types ___ Basic enum features When you create an enum, an associated class is produced for you by the compiler. This class is automatically ...


Enumerated Types


Basic enum features

  • When you create an enum, an associated class is produced for you by the compiler. This class is automatically inherited from java.lang.Enum.
  • The ordinal( ) method produces an int indicating the declaration order of each enum instance, starting from zero.

Using static imports with enums

  • Is it better to be explicit and qualify all enum instances? It probably depends on the complexity of your code.

Adding methods to an enum

  • Except for the fact that you can’t inherit from it, an enum can be treated much like a regular class.
  • You may want to produce different descriptions for an enumeration than the default toString( ).
  • If you are going to define methods you must end the sequence of enum instances with a semicolon.
  • Java forces you to define the instances as the first thing in the enum.
  • The constructor can only be used to create the enum instances that you declare inside the enum definition.
  • The compiler won’t let you use it to create any new instances once the enum definition is complete.

Overriding enum methods

  • Overriding the toString( ) method for an enum is the same as overriding it for a regular class.

enums in switch statements

  • Ordinarily, a switch only works with an integral value, but since enums have an established integral order and the order of an instance can be produced with the ordinal( ) method, enums can be used in switch statements.
  • Although normally you must qualify an enum instance with its type, you do not have to do this in a case statement.
  • The compiler does not complain that there is no default statement inside the switch.
  • On the other hand, if you are calling return from case statements, the compiler will complain if you don’t have a default.

The mystery of values()

  • If you look at Enum, you’ll see that there is no values( ) method, even though we’ve been using it.
  • values( ) is a static method that is added by the compiler.
  • In the output, you can see that Explore has been made final by the compiler, so you cannot inherit from an enum.
  • Because values( ) is a static method inserted into the enum definition by the compiler, if you upcast an enum type to Enum, the values( ) method will not be available.
  • Even if values( ) is not part of the interface of Enum, you can still get the enum instances via the Class object.

Implements, not inherits

  • All enums extend java.lang.Enum. Since Java does not support multiple inheritance, this means that you cannot create an enum via inheritance.
  • It is possible to create an enum that implements one or more interfaces.

Using interfaces for organization

  • The motivation for inheriting from an enum comes partly from wanting to extend the number of elements in the original enum, and partly from wanting to create subcategories by using subtypes.
  • You can achieve categorization by grouping the elements together inside an interface and creating an enumeration based on that interface.
  • Another, more compact, approach to the problem of categorization is to nest enums within enums.

Using EnumSet instead of flags

  • An enum requires that all its members be unique, so it would seem to have set behavior, but since you can’t add or remove elements it’s not very useful as a set.
  • Internally, it is represented by (if possible) a single long that is treated as a bit-vector, so it’s extremely fast and efficient.
  • EnumSets are built on top of longs, a long is 64 bits, and each enum instance requires one bit to indicate presence or absence. This means you can have an EnumSet for an enum of up to 64 elements without going beyond the use of a single long.

Using EnumMap

  • An EnumMap is a specialized Map that requires that its keys be from a single enum.
  • An EnumMap can be implemented internally as an array.
  • You can only call put( ) for keys that are in your enum, but other than that it’s like using an ordinary Map.
  • The order of elements in the EnumMap is determined by their order of definition in the enum.
  • An EnumMap allows you to change the value objects, whereas constant-specific methods are fixed at compile time.

Constant-specific methods

  • You define one or more abstract methods as part of the enum, then define the methods for each enum instance.
  • You can look up and call methods via their associated enum instance.
  • Each instance is a distinct type.
  • You cannot treat enum instances as class types.
  • Because they are static, enum instances of inner enums do not behave like ordinary inner classes.
  • It is possible to override constant-specific methods, instead of implementing an abstract method.

Chain of Responsibility with enums

  • In the Chain of Responsibility design pattern, you create a number of different ways to solve a problem and chain them together.
  • When a request occurs, it is passed along the chain until one of the solutions can handle the request.
  • Each strategy is tried in turn until one succeeds or they all fail.

State machines with enums

  • Enumerated types can be ideal for creating state machines.
  • Because enums restrict the set of possible cases, they are quite useful for enumerating the different states and inputs.

Multiple dispatching

  • Java only performs single dispatching.
  • If you are performing an operation on more than one object whose type is unknown, Java can invoke the dynamic binding mechanism on only one of those types.
  • If you want double dispatching, there must be two method calls: the first to determine the first unknown type, and the second to determine the second unknown type.
  • Generally, you’ll set up a configuration such that a single method call produces more than one virtual method call and thus services more than one type in the process.

Dispatching with enums

  • You can’t use enum instances as argument types.
  • There are a number of different approaches to implementing multiple dispatching which benefit from enums.

Using constant-specific methods

  • Because constant-specific methods allow you to provide different method implementations for each enum instance, they might seem like a perfect solution for setting up multiple dispatching.

Dispatching with EnumMaps

  • It’s possible to perform a "true" double dispatch using the EnumMap class, which is specifically designed to work very efficiently with enums.

Using a 2-D array

  • A two-dimensional array mapping the competitors onto the outcomes produces the smallest and most straightforward solution.
  • It’s not quite as "safe" as the previous examples because it uses an array.
    

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天在看別人代碼時看到這樣一種寫法, 感覺是個挺容易踩到的坑, 搞清楚後寫出來備忘. 短路邏輯 Python中進行邏輯運算的時候, 預設採用的是一種叫做短路邏輯的運算規則. 名字是很形象的, 下麵直接看代碼 可以看到, 雖然1會被當做布爾值計算, 但整個表達式的計算結果卻不一定是布爾值, 而是根據表 ...
  • 現在的資料庫越來越多,如mgdb,我比較常用的是mysql,但有一天做項目需要連接SqlServer,就去找了個方法。找了很多無非就mssql模塊和node-sqlserver模塊,但node-sqlserver好像有很多限制和還要編譯,感覺很麻煩,就用了mssql模塊。mssql模塊還是很簡單的, ...
  • 一般的智能指針都是通過一個普通指針來初始化,所以很容易寫出以下的代碼: #include using namespace std; int func1(){ //返回一個整數的函數 } void func2(AutoPtr ptr,int t){ //一些操作 } int ... ...
  • (1)、編寫配置文件 Hibernate通過讀寫預設的XML配置文件hibernate.cfg.xml載入資料庫配置信息、代碼如下: (2)、編寫持久化類 持久化類是Hibernate操作的對象、它與資料庫中的數據表相對應 (3)、編寫映射文件 (4)、編寫Hibernate的工具類 ...
  • 下期預告,函數... ...
  • 題目大意:給定一個長度為n的整數序列x[i],確定一個二元組(b, k)使得S=Σ(k*i+b- x[i])^2(i∈[0,n-1])最小 看Claris大神的題解就行了。實際上就是用2次二次函數的性質。 http://www.cnblogs.com/clrs97/p/4703437.html 代碼 ...
  • 轉載http://blog.csdn.net/Shayabean_/article/details/44885917博客 先說說基數排序的思想: 基數排序是非比較型的排序演算法,其原理是將整數按位數切割成不同的數字,然後按每個位數分別比較。 將所有待比較數值(正整數)統一為同樣的數位長度,數位較短的數 ...
  • 什麼是Hibernate??? Hibernate是一個開放源代碼的對象關係映射框架,它對JDBC進行了非常輕量級的對象封裝,它將POJO與資料庫表建立映射關係,是一個全自動的orm框架,hibernate可以自動生成SQL語句,自動執行,使得Java程式員可以隨心所欲的使用對象編程思維來操縱資料庫 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...