enum与int、String之间的转换

本文详细介绍了枚举类型的使用方法,包括基本枚举的定义及操作、带参数枚举的实现方式,并提供了多个示例帮助理解如何将枚举类型应用于实际编程中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 参考:https://www.cnblogs.com/sunxucool/archive/2012/12/03/2800021.html

一、简单枚举

示例:

// 当枚举类只有一个属性时,这个枚举类是单例的
public enum Weather {
    winter,
    spring,
    summer,
    fall
}

1. 枚举转化成int

int i = Weather.winter.ordinal(); // => 0

2.int转化成枚举

Weather b= Weather.values()[0];

3.枚举转化成String

 String winter = Weather.winter.name(); // => winter

4. String转化成枚举

Weather weather = Weather.valueOf("spring");

二、带参数枚举

示例:

public enum BusinessType {
    USER_BUSINESS,
    ORDER_BUSINESS
}

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;
    }
 
}

1. int 转化成枚举

BusinessEnum business1 = BusinessEnum.getEnumByType(1); // => User

BusinessType type1 = business1.getBusinessType(); // => USER_BUSINESS

示例:

	public enum Lamtern {
		RED(200), YELLOW(30), GREEN(200);

		int time;

		private Lamtern(int time) {
			this.time = time;
		}

		public int getTime() {
			return time;
		}

		public void setTime(int time) {
			this.time = time;
		}

		public static Lamtern getLamtern(int time) {
			for (Lamtern c : Lamtern.values()) {
				if (c.getTime() == time) {
					return c;
				}
			}
			return null;
		}

	}

1.int转化成枚举

Lamtern lamtern = Lamtern.getLamtern(200);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值