且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

枚举和枚举之间的区别

更新时间:2023-02-15 17:11:58

包含 Enum.valueof()方法的原因是它适用于任何枚举。相比之下,特定方法的枚举 valueof 方法仅适用于特定的枚举 ...因为枚举类不能多态使用。



显然, Enum.valueOf(...)方法只有在实现需要的代码才能处理多个枚举时, code> types ...和泛型不剪切。


enum has valueOf(string) method to get enum constant and the same type of method present in java.lang.Enum class having name valueOf(enumClassName, string) I found both are giving same output. Then what are other differences. If no difference then why JSL added Enum.valueOf()?

enum Season {
    WINTER,SUMMER
}

class Test {
    public static void main(String[] args) {
        String season = "WINTER";

        //switch (Season.valueOf(colObject))  // following line achieves same thing
        switch (Enum.valueOf(Season.class, season)) // any other difference between both approach
        {
            case WINTER: {
                System.out.println("Got it in switch case= VENDOR");
                break;
            }
            default:
                System.out.println("Fell thru.");
                break;
            }
    }
}

The reason the Enum.valueof() method is included is that it works with any enum. By contrast, the enum valueof method for a specific method only works for that specific enum ... since enum classes cannot be used polymorphically.

Obviously the Enum.valueOf(...) method is only really useful if you are implementing code that needs to work for multiple enum types ... and generics don't cut it.