switch-case with a string and enum in java

huangapple go评论96阅读模式
英文:

switch-case with a string and enum in java

问题

我想在Java中使用switch-case检查具有枚举值的字符串所以我做了这样的操作

public enum DemoEnumType {

    ALL(""),
    TOP("acb"),
    BOTTOM("def");

    private String code;

    DemoEnumType(String code) {
        this.code = code;
    }

    public String code() {
        return this.code;
    }
}

当我运行这段代码时,它会抛出一个异常:

public class Demo {
    public static void main(String[] args) {
        DemoEnumType typeValue = DemoEnumType.valueOf("acb");
        
        switch (typeValue){
            case ALL:
                System.out.print("匹配");
            case BOTTOM:
                System.out.print("匹配");
            case TOP:
                System.out.print("匹配");
        }
    }
}

异常信息:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant package.DemoEnumType.acb.


<details>
<summary>英文:</summary>

I wanted to check a string with the value of enum in java using switch-case, so I did like this:

public enum DemoEnumType {

ALL(&quot;&quot;),
TOP(&quot;acb&quot;),
BOTTOM(&quot;def&quot;);

private String code;

DemoEnumType(String code) {
    this.code = code;
}

public String code() {
    return this.code;
}

}


and when I run this code it throws an exception:

public class Demo {
public static void main(String[] args) {
DemoEnumType typeValue = DemoEnumType.valueOf("acb");

    switch (typeValue){
        case ALL:
            System.out.print(&quot;match&quot;);
        case BOTTOM:
            System.out.print(&quot;match&quot;);
        case TOP:
            System.out.print(&quot;match&quot;);
    }

}

}

**Exeption:**

&gt;Exception in thread &quot;main&quot; java.lang.IllegalArgumentException: No enum constant package.DemoEnumType.acb.

</details>


# 答案1
**得分**: 2

```java
DemoEnumType typeValue = DemoEnumType.valueOf("acb");

没有具有值“acb”的枚举元素。如果没有具有给定名称的元素,Enum#valueOf 将抛出 IllegalArgumentException。您需要使用 ALLBOTTOMTOP

DemoEnumType type = DemoEnumType.valueOf("ALL");

或者,您可以使用一个 String 到 DemoEnumType 的 Map 进行 O(1) 查找,并使用您提供的值。

Map<String, DemoEnumType> valueToType = Stream.of(DemoEnumType.values())
        .collect(Collectors.toMap(DemoEnumType::code, Function.identity()));

DemoEnumType type = valueToType.get("abc");
英文:
DemoEnumType typeValue = DemoEnumType.valueOf(&quot;acb&quot;);

No enum element exists with the value acb. Enum#valueOf will throw an IllegalArgumentException if no element exists with the given name. You need to use ALL, BOTTOM, or TOP.

DemoEnumType type = DemoEnumType.valueOf(&quot;ALL&quot;);

Alternatively, you could use a Map of String to DemoEnumType for O(1) lookup and use the values you've provided.

Map&lt;String, DemoEnumType&gt; valueToType = Stream.of(DemoEnumType.values())
        .collect(Collectors.toMap(DemoEnumType::code, Function.identity());

DemoEnumType type = valueToType.get(&quot;abc&quot;);

答案2

得分: 1

你的枚举成员是ALL、TOP和BOTTOM,而不是字符串值。你只能将它们传递给valueOf()方法。

要使用字符串值,你可以在枚举中创建一个方法,该方法接收一个字符串,并返回相应的枚举值。

英文:

Your Enum members are ALL, TOP and BOTTOM, not the string values. you can only pass then to valueOf().

To use the string values you can create a method in your Enum that receives a String and returns the appropriate Enum

huangapple
  • 本文由 发表于 2020年8月20日 20:29:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63505142.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定