「Java基础入门」Java中switch怎么使用枚举

566 阅读2分钟

在Java开发中,switch语句是一种常用的流控制语句,用于根据不同的条件执行不同的代码块。而当使用枚举类型作为条件时,我们常常会遇到“Constant expression required”的报错问题,这给程序开发造成了不小的困扰。

switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。 我们创建一个枚举:

@Getter
@AllArgsConstructor
public enum ProductEnum {

	TYPE_1(1,"精品推荐"),
	TYPE_2(2,"热门榜单"),
	TYPE_3(3,"首发新品"),
	TYPE_4(4,"猜你喜欢");


	private Integer value;
	private String desc;
}

用switch语句:

 int a = 0;
        // order
        switch (a) {
            //精品推荐
            case ProductEnum.TYPE_1.getValue():
                System.out.println("1");
                break;
            //首发新品
            case ProductEnum.TYPE_2.getValue():
                System.out.println("1");
                break;
            // 猜你喜欢
            case ProductEnum.TYPE_3.getValue():
                System.out.println("1");
                break;
            // 热门榜单
            case ProductEnum.TYPE_4.getValue():
                System.out.println("1");
                break;
        }

看上去没有问题,但是因为switch中需要的是一个常量,但是枚举中又是不可以加final关键字,所以会出现这种情况:(Constant expression required:需要常量表达式在这里插入图片描述

我们想要使用就需要封装一个方法在枚举类里面:

	public static ProductEnum toType(int value) {
		return Stream.of(ProductEnum.values())
				.filter(p -> p.value == value)
				.findAny()
				.orElse(null);
	}

封装后的枚举类:

@Getter
@AllArgsConstructor
public enum ProductEnum {

	TYPE_1(1,"精品推荐"),
	TYPE_2(2,"热门榜单"),
	TYPE_3(3,"首发新品"),
	TYPE_4(4,"猜你喜欢");


	private Integer value;
	private String desc;

	public static ProductEnum toType(int value) {
		return Stream.of(ProductEnum.values())
				.filter(p -> p.value == value)
				.findAny()
				.orElse(null);
	}


}

这个时候我们这么用:

   int a = 0;
        switch (ProductEnum.toType(a)) {
            //精品推荐
            case TYPE_1:
                System.out.println("1");
                break;
            //首发新品
            case TYPE_3:
                System.out.println("2");;
                break;
            // 猜你喜欢
            case TYPE_4:
                System.out.println("3");
                break;
            // 热门榜单
            case TYPE_2:
                System.out.println("4");
                break;
        }

这样就没问题啦: 在这里插入图片描述

当我们在处理枚举类型时,遇到了“需要常量表达式”的问题。针对这个问题,我们可以按照上述方法进行处理,将枚举的值转化成枚举类型,来避免编译错误。

除此之外,值得一提的是,在实际应用中,枚举也是一种非常重要的数据类型。它可以用于表示各种状态、选项以及配置项,还可以为程序中的常量命名,以减少硬编码。因此,熟练掌握枚举类型的相关操作,是我们开发高效、优质代码所必不可少的基本技能。

总之,本文向大家介绍了如何在Java开发中处理枚举类型,让大家更好地理解和掌握switch语句的使用方法。希望大家能够通过学习和实践,巩固这些基础知识,并在日常工作中充分发挥它们的应用价值,为自己的开发工作提升整体效率与质量。