Why can't I use switch statement on a String?

前端 未结 16 2048
面向向阳花
面向向阳花 2020-11-21 07:57

Is this functionality going to be put into a later Java version?

Can someone explain why I can\'t do this, as in, the technical way Java\'s switch state

16条回答
  •  旧巷少年郎
    2020-11-21 08:07

    Beside the above good arguments, I will add that lot of people today see switch as an obsolete remainder of procedural past of Java (back to C times).

    I don't fully share this opinion, I think switch can have its usefulness in some cases, at least because of its speed, and anyway it is better than some series of cascading numerical else if I saw in some code...

    But indeed, it is worth looking at the case where you need a switch, and see if it cannot be replaced by something more OO. For example enums in Java 1.5+, perhaps HashTable or some other collection (sometime I regret we don't have (anonymous) functions as first class citizen, as in Lua — which doesn't have switch — or JavaScript) or even polymorphism.

提交回复
热议问题