enum与int、String之间的转换

mac2022-06-30  23

enum<->int

enum -> int: int i = enumType.value.ordinal();int -> enum: enumType b= enumType.values()[i];

 

enum<->String

enum -> String: enumType.name()

String -> enum: enumType.valueOf(name);

 --------------------------------------------------------------------------

http://stackoverflow.com/questions/604424/java-enum-converting-string-to-enum

有时间整理测试一下这个帖子中的内容,同事参考《Effective Java中文版第2版》第30条内容,更新本帖。

---------------------------------------------------------------------------

下面是Enum和字符串类型转化的例子。

第一个例子:字符串和枚举值不相同,注意覆盖toString方法。 import java.util.HashMap;import java.util.Map; /* * * * @author admin  */ public   enum  Blah {    A( " text1 " ),    B( " text2 " ),    C( " text3 " ),    D( " text4 " );         private  String text;        Blah(String text) {         this .text  =  text;    }         public  String getText() {         return   this .text;    }         //  Implementing a fromString method on an enum type      private   static  final Map < String, Blah >  stringToEnum  =   new  HashMap < String, Blah > ();     static  {         //  Initialize map from constant name to enum constant          for (Blah blah : values()) {            stringToEnum.put(blah.toString(), blah);        }    }         //  Returns Blah for string, or null if string is invalid      public   static  Blah fromString(String symbol) {         return  stringToEnum. get (symbol);    }    @Override     public  String toString() {         return  text;    }}

 第2个例子,字符串和枚举值相同,这个更为简单。

 

import java.util.HashMap;import java.util.Map; /* * * * @author admin  */ public   enum  Blah {    A,    B,    C,    D;     //  Implementing a fromString method on an enum type      private   static  final Map < String, Blah >  stringToEnum  =   new  HashMap < String, Blah > ();     static  {         //  Initialize map from constant name to enum constant          for (Blah blah : values()) {            stringToEnum.put(blah.toString(), blah);        }    }         //  Returns Blah for string, or null if string is invalid      public   static  Blah fromString(String symbol) {         return  stringToEnum. get (symbol);    }}

 

 至于整形和Enum之间的转换,也可类似处理。

 

 

转载于:https://www.cnblogs.com/cuizhf/archive/2011/08/22/2150046.html

相关资源:Java Enum和String及int的相互转化示例
最新回复(0)