table

java enum type

在像C这样强调数据结构的语言里,枚举是必不可少的一种数据类型。然而在java的早期版本中,是没有一种叫做enum的独立数据结构的。所以在以前的java版本中,我们经常使用interface来simulate一个enum。
java 代码
  1. public interface Color {   
  2.     static int RED   = 1;   
  3.     static int GREEN     = 2;   
  4.     static int BLUE = 3;   
  5. }  

虽然这种simulation比较麻烦,但在以前也还应付的过去。可是随着java语言的发展,越来越多的呼声要求把enum这种数据结构独立出来,加入到java中。所以从java 1.5以后,就有了enum,这也是这篇blog要学习的topic。

学习的最好方式就是例子,先来一个:

java 代码
  1. public class EnumDemo {   
  2.     private enum Color {red, blue, green}//there is not a ";"   
  3.        
  4.     public static void main(String[] args) {   
  5.         for(Color s : Color.values()) {   
  6.             //enum的values()返回一个数组,这里就是Seasons[]   
  7.              System.out.println(s);   
  8.          }   
  9.      }   
  10. }  
console results
  1. red   
  2. blue   
  3. green  

注意事项已经在code中注释出,还要说明一点的是,这个java文件编译完成后不只有一个EnumDemo.class,还会有一个EnumDemo$Seasons.class,奇怪吧!

Another e.g.

java 代码
  1. public class EnumDemo {   
  2.     private enum Color {red, blue, green}//there is not a ";"   
  3.        
  4.     public static void main(String[] args) {   
  5.          Color s = Color.blue;   
  6.            
  7.         switch (s) {   
  8.         case red://notice: Seasons.red will lead to compile error   
  9.              System.out.println("red case");   
  10.             break;   
  11.         case blue:   
  12.              System.out.println("blue case");   
  13.             break;   
  14.         case green:   
  15.              System.out.println("green case");   
  16.             break;   
  17.         default:   
  18.             break;   
  19.          }   
  20.      }   
  21. }  

这个例子要说明的就是case的情况。

就这么多吗,当然不是,我们的enum结构还可以定义自己的方法和属性。

java 代码
  1. public class EnumDemo {   
  2.     private enum Color {   
  3.          red, blue, green;//there is a ";"   
  4.            
  5.         //notic: enum's method should be "static"   
  6.         public static Color getColor(String s){   
  7.             if(s.equals("red flag")){   
  8.                 return red;   
  9.              } else if(s.equals("blue flag")){   
  10.                 return blue;   
  11.              } else {   
  12.                 return green;   
  13.              }   
  14.          }   
  15.      }//there is not ";"   
  16.        
  17.     public static void main(String[] args) {   
  18.          EnumDemo demo = new EnumDemo();   
  19.          System.out.println(demo.getFlagColor("red flag"));   
  20.      }   
  21.        
  22.     public Color getFlagColor(String string){   
  23.         return Color.getColor(string);   
  24.      }   
  25. }  

Ok,so much for enum. Isn't it simple?

posted on 2008-12-15 10:31 小卓 阅读(212) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: