开发者

Possible to have switch(java.lang.Object) in java?

开发者 https://www.devze.com 2023-01-29 01:27 出处:网络
My application required to have switch case statement of type String. I need something like this: Object list1 = \"list1\";

My application required to have switch case statement of type String.

I need something like this:

    Object list1 = "list1";
    Object list2 = "开发者_如何学运维list2";
    Object list3 = "list3";

    Object option = "list1";
    switch (option) {
        case list1: // Do something
        case list2: // Do something
        case list3: // Do something
        default:    // Do something
    }

Is it possible to have?

EDIT:

Is it better to use switch case for n conditions rather going with if and else? Please comment on it?


Since you are switching on Strings I assume that the strings are known at compile time. In that case you can use an enum.

    public enum MyStrings{

        LIST1, LIST2
    }

Then

    switch(MyStrings.valueOf(option)){

         case LIST1: do something; break;
         //etc.
    }


In the JDK 7 release, you can use a String object in the expression of a switch statement: http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html


See this question: Why can't I switch on a String?

Not currently supported, but expected to be in Java 7.

Edit: actually appears to be Strings only, not any Objects

Perhaps each object should implement a method that contains the logic you're trying to put into the switch statement?


No, you can't do this (try it and find out). But if you want this, perhaps a Map such as a HashMap would better suit your purposes.


No, use other collections like Hashmap or use array indexes to do the same, create an array of elements and put a switch case on index


The switch can be supported for checking String, Integer and other primitive data types, but it is not approve successful in objects comparisons.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号