可以在java中使用switch(java.lang.Object)吗? [英] Possible to have switch(java.lang.Object) in java?
本文介绍了可以在java中使用switch(java.lang.Object)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的应用程序需要具有 String
类型的switch case语句。
My application required to have switch case statement of type String
.
我需要这样的东西:
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
}
有可能吗?
编辑:
为<$ c $使用开关案例是否更好? c> n 条件而不是,如果
和 else
?请评论它?
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
}
然后
switch(MyStrings.valueOf(option)){
case LIST1: do something; break;
//etc.
}
这篇关于可以在java中使用switch(java.lang.Object)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文