枚舉類型(enum type)是指由一組固定的常量組成合法的類型。Java中由關(guān)鍵字enum來定義一個(gè)枚舉類型。
1、通過關(guān)鍵字enum定義枚舉類型
public enum Season {
SPRING, SUMMER, AUTUMN, WINER;
}
2、枚舉類型默認(rèn)方法
創(chuàng)建enum時(shí),編譯器會(huì)為你生成一個(gè)相關(guān)的類,這個(gè)類繼承java.lang.Enum。
枚舉類型方法.png
另外還有神秘的方法:values()
3、用法
3.1、定義常量
3.2、switch語句
enum Signal { GREEN, YELLOW, RED}
public class TrafficLight {
Signal color = Signal.RED;
public void change() {
switch (color) {
case RED:
color = Signal.GREEN; break;
case YELLOW:
color = Signal.RED; break;
case GREEN:
color = Signal.YELLOW; break;
}
}
@Override public String toString() {
return "The traffic light is "+color;
}
public static void main(String[] args) {
TrafficLight trafficLight = new TrafficLight();
for(int i = 0; i < 4;i++){
System.out.println(trafficLight);
trafficLight.change();
}
}
}
3.3 向enum中添加新方法
// 定義 RSS(Really Simple Syndication) 種子的枚舉類型
public enum NewsRSSFeedEnum {
/ / 雅虎頭條新聞 RSS 種子
YAHOO_TOP_STORIES("http://rss.news.yahoo.com/rss/topstories"),
//CBS 頭條新聞 RSS 種子
CBS_TOP_STORIES("http://feeds.cbsnews.com/CBSNewsMain?format=xml"),
// 洛杉磯時(shí)報(bào)頭條新聞 RSS 種子
LATIMES_TOP_STORIES("http://feeds.latimes.com/latimes/news?format=xml");
// 枚舉對象的 RSS 地址的屬性
private String rss_url;
// 枚舉對象構(gòu)造函數(shù)
private NewsRSSFeedEnum(String rss) {
this.rss_url = rss;
}
// 枚舉對象獲取 RSS 地址的方法
public String getRssURL() {
return this.rss_url;
}
}
3.4 不同枚舉實(shí)例具有不同行為
public enum ConstantSpecificMethod {
DATA_TIME{
String getInfo(){
return DateFormat.getDateInstance().format(new Date());
}
},
CLASSPATH{
String getInfo(){
return System.getenv("CLASSPATH");
}
};
abstract String getInfo();
public static void main(String[] args) {
for(ConstantSpecificMethod csm: values()){
System.out.println(csm.getInfo());
}
}
}
3.5 使用枚舉創(chuàng)建單例
public class EnumSingleton {
private EnumSingleton(){}
public static EnumSingleton getInstance(){
return Singleton.INSTANCE.getInstance();
}
private static enum Singleton{
INSTANCE;
private EnumSingleton singleton; //JVM會(huì)保證此方法絕對只調(diào)用一次
private Singleton(){
singleton = new EnumSingleton();
}
public EnumSingleton getInstance(){
return singleton;
}
}
}
EnumSet和EnumMap
- EnumSet方法
EnumSet方法.png
- EnumMap
EnumMap.png