枚举的总结

来源:互联网 发布:mac系统恢复u盘制作 编辑:程序博客网 时间:2024/05/16 05:12
 

枚举:

switch()后面只能跟byte,char,short,int类型的,还可以是枚举,不能是String,long类型的。

 

//枚举的使用switch()后面只能跟byte,char,short,int类型的,还可以是枚举,不能是String,long类型的。

//枚举的基本使用

public enum Color

{

       Red, White, Blue, Black

}

 

public class ColorTest

{

       public static void main(String[] args)

       {

              Color myColor = Color.Blue;

             

              System.out.println(myColor);

             

              System.out.println("----------------");

             

              for(Color color : Color.values())

              {

                     System.out.println(color);

              }

       }

}

 

// 枚举的构造方法,必须跟对象的赋值一致

public enum Coin

{

       penny("hello"), nickel("world"), dime("welcome"), quarter("hello world");

      

       private String value;

      

       public String getValue()

       {

              return value;

       }

      

       Coin(String value)

       {

              this.value = value;

       }

      

       public static void main(String[] args)

       {

              Coin coin = Coin.quarter;

             

              System.out.println(coin.getValue());

       }

}

 

public class EnumTest

{

       public static void doOp(OpConstant opConstant)

       {

              switch (opConstant)

              {

              case TURN_LEFT:

                     System.out.println("向左转");

                     break;

 

              case TURN_RIGHT:

                     System.out.println("向右转");

                     break;

 

              case SHOOT:

                     System.out.println("射击");

                     break;

              }

       }

      

      

       public static void main(String[] args)

       {

              doOp(OpConstant.TURN_LEFT);

       }    

}

 

enum OpConstant

{

       TURN_LEFT, TURN_RIGHT, SHOOT

}

 

 

//enum的遍历.values()显示enum中的所有对象

public class ShowEnum2

{

       public static void main(String[] args)

       {

              for(OpConstant c : OpConstant.values())//

              {

                   System.out.printf("%d, %s, %n", c.ordinal(), c);//这是格式化操作,%d表示整型输出,%s表示字符串输出,%n表示换行,c.ordinal()输出返回枚举常量的序数

              }

       }

}

 

//枚举的比较,就是对象的比较

public static void main(String[] args)

       {

           enumCompareTo(OpConstant.valueOf(args[0]));//将里面的字符参数包装成enum类型

       }

      

       public static void enumCompareTo(OpConstant constant)

       {

           System.out.println(constant);

          

           for(OpConstant c : OpConstant.values())

           {

              System.out.println(constant.compareTo(c));

           }

       }

 

输出结果:TURN_RIGHT 或者 TURN_LEFT

1  或者2

0   或者1

-1   或者0

原创粉丝点击