java中枚举类型的简单使用

来源:互联网 发布:c2c电商市场份额 淘宝 编辑:程序博客网 时间:2024/05/17 08:52

 * 1. enum has equal position to class and interface

枚举类型和class海油interface具有对等的地位,不要把它和int String 类型等同起来,这一点从它的形式就可以看出来

 * 2. each content in enum has a index of int type

在枚举类中,每一个枚举项都有一个int类型的值与之对应,可以把枚举类型中的内容看做一个数组,数组下标从0开始

 * 3. the method values() return the array of enum type

values()方法返回枚举类型的数组

 * 4. the method valueOf() can convert String type to enum type

valueOf(String str)方法可以将字符串转化为枚举类型,注意这里的字符串必须在枚举类型的内容中包含

 * 5. in fact, the method compareTo() used in comparing the index of enum object 

compareTo()比较的是枚举类型在枚举类中对应的下标a.compareTo(b)   相当于a.index - b.index

 * 6. the method ordinal() return the index

ordinal()返回枚举类型对象对应的下标

/** *  * @author zero * 1. enum has equal position to class and interface * 2. each content in enum has a index of int type * 3. the method values() return the array of enum type * 4. the method valueOf() can convert String type to enum type * 5. in fact, the method compareTo() used in comparing the index of enum object   * 5. the method ordinal() return the index  */public class EnumerationTest {public enum Season {Spring,Summer,Autumn,Winter}public static void main(String[] args) {for(Season test : Season.values()) {System.out.print(test + " ");}Season autumnSeason  = Season.valueOf("Autumn");System.out.println("\n" + autumnSeason + ":" + autumnSeason.ordinal());for(Season test : Season.values()) {System.out.println(autumnSeason + "----" + test + ":" + autumnSeason.compareTo(test));}}}

运行结果:

Spring Summer Autumn Winter
Autumn:2
Autumn----Spring:2
Autumn----Summer:1
Autumn----Autumn:0
Autumn----Winter:-1

0 0
原创粉丝点击