java中枚举类型的简单使用

 * 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值