Linux安全网 - Linux操作系统_Linux 命令_Linux教程_Linux黑客

会员投稿 投稿指南 本期推荐:
搜索:
您的位置: Linux安全网 > Linux编程 > » 正文

So how to declare a const table in Java?

来源: 未知 分享至:

Often we see people do it this way,

public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL   = 3;
This pattern has many problems, such as:
  • Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
  • No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
  • Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.


So why not use the enum type,

    public enum UnitType {

          MARINE, TANK

    }

 

Java enum type are very different from C/C++. Java treats enumerations as a type separate from integers, and intermixing of enum and integer values is not allowed. In fact, an enum type in Java is actually a special compiler-generated class rather than an arithmetic type.

 

 So if you want to have medic as 4, you have to put 2 undefined item in between.

    public enum UnitType {

        MARINE, TANK, UNDEFINED, UNDEFINED, MEDIC

    }

 

That's why people don't often use the .ordinal() thing. Cuz it's too hard to handle, and Enumerated types are Comparable, using the internal integer; as a result, they can be sorted. So if you trying to write some functions that need the ordinal as input, and in the meanwhile your ordinal is changing. It's easy to see that your program will get messed up.

 

So we turn to use constructor and local variable and its getter, like this:


    public enum UnitType {
        MARINE(1), TANK(2);
       
        private final int typeID;
        UnitType(int number) {this.typeID = number;}
       
        public int getTypeID() {return this.typeID;}
    }

when we want to use its number, we can call UnitType.MARINE.getTypeID()

 

make use of valueOf

System.out.println("marine type id is " + UnitType.valueOf("MARINE").getTypeID());
        

 

Java 5.0 enumerations also can be used in switch statements, a nice convenience. Note that the enumeration values are still static class members, though not declared as such.

 

 

Reminders :

  • enums are implicitly final subclasses of java.lang.Enum
  • if an enum is a member of a class, it is implicitly static
  • new can never be used with an enum, even within the enum type itself
  • name and valueOf simply use the text of the enum constants, while toString may be overridden to provide any content, if desired
  • for enum constants, equals and == amount to the same thing, and can be used interchangeably
  • enum constants are implicitly public static final
  • the order of appearance of enum constants is called their "natural order", and defines the order used by other items as well : compareTo, iteration order of values , EnumSet, EnumSet.range.


 

 // play around with this code:)


import java.util.EnumSet;

public class main {

    enum UnitType {
        MARINE(1), TANK(2);
       
        private final int typeID;
        UnitType(int number) {this.typeID = number;}
       
        public int getTypeID() {return this.typeID;}
    }
   
    enum OperatingSystems {
        windows, unix, linux, macintosh;
       
        public static final EnumSet<OperatingSystems> unixLike = EnumSet.range(unix, macintosh);
       
        public final boolean supportCommandLine() {
            return unixLike.contains(this);
        }
       
       
        public static final EnumSet<OperatingSystems> os = EnumSet.allOf(OperatingSystems.class);
    }
  
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println("Hello World!");
       
        System.out.println(UnitType.TANK +" type id is " + UnitType.valueOf("TANK").getTypeID());
       
       
        for(OperatingSystems os: OperatingSystems.os) {
            System.out.println(String.format("%d. %s Scholars " + (os.supportCommandLine()? "love it":"hate it") + ".",
                                            os.ordinal() + 1, os));
        }
       
       
       
    }
   
   


}

 

 


Tags:
分享至:
最新图文资讯
1 2 3 4 5 6
验证码:点击我更换图片 理智评论文明上网,拒绝恶意谩骂 用户名:
关于我们 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 发展历史