Using string representations of enum values in switch-case

前端 未结 3 1522
清酒与你
清酒与你 2020-12-31 04:06

Why is it not possible to use enum values as strings in a switch case? (Or what is wrong with this:)

String argument;
switch (argument) {
    case MyEnum.V         


        
3条回答
  •  灰色年华
    2020-12-31 05:05

    case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ?

    No, not necessarily: you are free to provide your own implementation of toString()

    public enum MyType {
    VALUE1 {
        public String toString() {
            return "this is my value one";
        }
    },
    
    VALUE2 {
        public String toString() {
            return "this is my value two";
        }
    }
    

    }

    Moreover, someone who is maintaining your code could add this implementation after you leave the company. That is why you should not rely on String values, and stick to using numeric values (as represented by the constants MyEnum.VALUE1, MyEnum.VALUE2, etc.) of your enums instead.

提交回复
热议问题