java - 如何让 switch case 在 Java 中接受多种数据类型?

标签 java language-features switch-statement

虽然使用 Java switch case,它只接受 char 和 int,但我想提供字符串 case。如何做到这一点?

最佳答案

你不能在 switch-case 中有字符串(目前)。 It's on its way in Java 7.

目前接受的类型包括char, byte, short, int, Character ByteShortInteger 或枚举类型。

来自 Java 语言规范:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type (§8.9), or a compile-time error occurs.

...

All of the following must be true, or a compile-time error will result:

  • Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.
  • No switch label is null.
  • No two of the case constant expressions associated with a switch statement may have the same value.
  • At most one default label may be associated with the same switch statement.

关于java - 如何让 switch case 在 Java 中接受多种数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2987556/

相关文章:

java - 如何在 Jersey 2.12 中获取 HK2 ServiceLocator?

java - 使用 Java 和 IText,如何从 PDF 中提取 AcroForm 字段名称?

Java类路径问题

java - java.lang.Math.PI 等于 GCC 的 M_PI 吗?

java - 如何使用 Mule ESB 在 smtp 中添加多个邮件附件

c++ - 为什么 constexpr 不能应用于构造函数?

c# - 枚举定义中的波浪号 (~) 是什么?

c - 具有重叠操作的 Switch 中的多个案例

c++ - 开关中的条件初始化

java - 用数组方法切换