13

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?

GROX13
  • 4,605
  • 4
  • 27
  • 41
Mohamed Saligh
  • 12,029
  • 19
  • 65
  • 84
  • You can also use polymorphism : http://stackoverflow.com/questions/1425659/alternative-to-switch-case-in-java/1425684#1425684 – OscarRyz Dec 04 '10 at 18:00

6 Answers6

12

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.
    }
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
4

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

gerdkolano
  • 43
  • 4
3

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?

Community
  • 1
  • 1
Brad Mace
  • 27,194
  • 17
  • 102
  • 148
1

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

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

Varun
  • 5,001
  • 12
  • 54
  • 85
0

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

htlbydgod
  • 330
  • 2
  • 8