java 中枚举类型,整型,字符串之间转换

先说说简单的枚举类型,与字符串,整型之间的转换。

可以理解为,枚举,就是一个简单的数组

public enum Weather {
	winter,
	spring,
	summer,
	fall
}

  

public class EnumDemo {
	public static void main(String[] args) {
//		System.out.println();
		
		//枚举转换整型
		int winter = Weather.winter.ordinal();
		System.out.println(winter);
		System.out.println(Weather.spring.ordinal());
		System.out.println(Weather.summer.ordinal());
		System.out.println(Weather.fall.ordinal());
		//枚举转换字符串。
		String win = Weather.winter.toString();
		String win2 = Weather.winter.name();
		System.out.println(win);
		System.out.println(win2);
		
		//字符转换枚举
		Weather weather = Weather.valueOf("spring");
		System.out.println(weather);
		
		//整型转换枚举
		int winter0 = 2;
		Weather weather2 = Weather.values()[winter0];
		
		System.out.println(weather2);
		
	}
}

  

带参数枚举

 

public enum BusinessEnum {
	User(1, BusinessType.USER_BUSINESS),
	Order(2, BusinessType.ORDER_BUSINESS);

	private int type;
	private BusinessType businessType;

	private BusinessEnum(int type, BusinessType businessType) {
		this.type = type;
		this.businessType = businessType;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public BusinessType getBusinessType() {
		return businessType;
	}

	public void setBusinessType(BusinessType businessType) {
		this.businessType = businessType;
	}

	public static BusinessEnum getEnumByType(int type) {
		for (BusinessEnum bt : values()) {
			if (bt.type == type) {
				return bt;
			}
		}
		return null;
	}

}

  

public enum BusinessType {
	USER_BUSINESS,
	ORDER_BUSINESS
}

  demo:

public class BusinessEnumDemo {
	public static void main(String[] args) {
//		System.out.println();
		
		BusinessEnum business1 = BusinessEnum.getEnumByType(1);
		BusinessEnum business2 = BusinessEnum.getEnumByType(2);
		
		System.out.println(business1);
		System.out.println(business2);
		
		BusinessType type1 = business1.getBusinessType();
		BusinessType type2 = business2.getBusinessType();
		System.out.println(type1);
		System.out.println(type2);
	}
}

  输出:

User
Order
USER_BUSINESS
ORDER_BUSINESS

  

 

转载于:https://www.cnblogs.com/myJavaCareerLife-yewei/p/8109661.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值