java为什么需要枚举_java – 什么是枚举,为什么它们有用?
當變量(特別是方法參數(shù))只能從一組可能的值中取出一個時,應該總是使用枚舉。示例將是類型常量(合同狀態(tài):“永久”,“臨時”,“學徒”)或標志(“立即執(zhí)行”,“延遲執(zhí)行”)。
如果使用枚舉而不是整數(shù)(或字符串代碼),則增加了編譯時檢查,避免傳入無效常量的錯誤,并記錄哪些值是合法使用的。
BTW,過度使用枚舉可能意味著你的方法太多了(通常最好有幾個單獨的方法,而不是一個方法,需要幾個標志,它修改它的作用),但如果你必須使用標志或類型代碼,枚舉是要走的路。
例如,哪個更好?
/** Counts number of foobangs.
* @param type Type of foobangs to count. Can be 1=green foobangs,
* 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
* @return number of foobangs of type
*/
public int countFoobangs(int type)
與
/** Types of foobangs. */
public enum FB_TYPE {
GREEN, WRINKLED, SWEET,
/** special type for all types combined */
ALL;
}
/** Counts number of foobangs.
* @param type Type of foobangs to count
* @return number of foobangs of type
*/
public int countFoobangs(FB_TYPE type)
一個方法調(diào)用:
int sweetFoobangCount = countFoobangs(3);
然后變成:
int sweetFoobangCount = countFoobangs(FB_TYPE.SWEET);
在第二個例子中,它立即清楚哪些類型是允許的,docs和實現(xiàn)不能失去同步,編譯器可以強制這樣做。
此外,一個無效的調(diào)用像
int sweetFoobangCount = countFoobangs(99);
不再可能。
總結(jié)
以上是生活随笔為你收集整理的java为什么需要枚举_java – 什么是枚举,为什么它们有用?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python编写arcgis脚本教程_A
- 下一篇: 复制密钥文件到另一台服务器,使用所有ss