正在阅读:JDK5.0的11个主要新特征JDK5.0的11个主要新特征

2006-02-22 09:58 出处: 作者:kmlzkma 责任编辑:xietaoming

6 枚举类(Enumeration Classes)

  用法:public enum Name {types, ….}

  简单的例子:

public enum Colors {Red, Yellow, Blue, Orange, Green, Purple, Brown, Black}

public static void main(String[] args){
    Colors myColor = Colors.Red;
    System.out.println(myColor);
}

  又一个简单例子:

import java.util.*;

enum OperatingSystems {windows, unix, linux, macintosh}
public class EnumExample1 {
    public static void main(String args[])  {
        OperatingSystems os;
        os = OperatingSystems.windows;
        switch(os) {
            case windows:
                System.out.println(“You chose Windows!”);
                break;
            case unix:
                System.out.println(“You chose Unix!”);
                break;
            case linux:
                System.out.println(“You chose Linux!”);
                break;
            case macintosh:
                System.out.println(“You chose Macintosh!”);
                break;
            default:
                System.out.println(“I don’t know your OS.”);
                break;
        }
    }
}

  应运enum简写的例子:

import java.util.*;

public class EnumTest
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
      String input = in.next().toUpperCase();
      Size size = Enum.valueOf(Size.class, input);
      System.out.println("size=" + size);
      System.out.println("abbreviation=" + size.getAbbreviation());
      if (size == Size.EXTRA_LARGE)
         System.out.println("Good job--you paid attention to the _.");
   }
}

enum Size
{
   SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

   private Size(String abbreviation) { this.abbreviation = abbreviation; }
   public String getAbbreviation() { return abbreviation; }
   private String abbreviation;
}

  enum类中拥有方法的一个例子:

enum ProgramFlags {

    showErrors(0x01),
    includeFileOutput(0x02),
    useAlternateProcessor(0x04);
    private int bit;
    ProgramFlags(int bitNumber) {
        bit = bitNumber;
    }
    public int getBitNumber()   {
        return(bit);
    }
}
public class EnumBitmapExample {
    public static void main(String args[])  {
        ProgramFlags flag = ProgramFlags.showErrors;
        System.out.println(“Flag selected is: “ +
        flag.ordinal() +
        “ which is “ +
        flag.name());
    }
}

键盘也能翻页,试试“← →”键

相关文章

关注我们

最新资讯离线随时看 聊天吐槽赢奖品