woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

java enum 学习

在像C这样强调数据结构的语言里,枚举是必不可少的一种数据类型。然而在java的早期版本中,是没有一种叫做enum的独立数据结构的。所以在以前的java版本中,我们经常使用interfacesimulate一个enum

java 代码

 

    public interface Color {  

        static int RED  = 1;  

        static int GREEN    = 2;  

        static int BLUE = 3;  

    } 

 

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

 

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

java 代码

 

    public class EnumDemo {  

        private enum Color {red, blue, green}//there is not a ";"  

          

        public static void main(String[] args) {  

            for(Color s : Color.values()) {  

                //enumvalues()返回一个数组,这里就是Seasons[]  

                System.out.println(s);  

            }  

        }  

   } 

 

console results

 

    red  

    blue  

    green 

 

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

 

Another e.g.

java 代码

 

    public class EnumDemo {  

        private enum Color {red, blue, green}//there is not a ";"  

          

        public static void main(String[] args) {  

            Color s = Color.blue;  

              

            switch (s) {  

            case red://notice: Seasons.red will lead to compile error  

                System.out.println("red case");  

               break;  

           case blue:  

               System.out.println("blue case");  

               break;  

           case green:  

               System.out.println("green case");  

               break;  

           default:  

               break;  

           }  

       }  

   } 

 

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

 

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

java 代码

 

    public class EnumDemo {  

        private enum Color {  

            red, blue, green;//there is a ";"  

              

            //notic: enum's method should be "static"  

            public static Color getColor(String s){  

                if(s.equals("red flag")){  

                    return red;  

                } else if(s.equals("blue flag")){  

                   return blue;  

               } else {  

                   return green;  

               }  

           }  

       }//there is not ";"  

         

       public static void main(String[] args) {  

           EnumDemo demo = new EnumDemo();  

           System.out.println(demo.getFlagColor("red flag"));  

      }  

         

       public Color getFlagColor(String string){  

           return Color.getColor(string);  

       }  

   } 

 

Okso much for enum. Isn't it simple?

posted on 2009-08-17 11:40 肥仔 阅读(707) 评论(0)  编辑 收藏 引用 所属分类: Web-后台


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理