java 中可以有 switch(java.lang.Object) 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4354662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Possible to have switch(java.lang.Object) in java?
提问by Mohamed Saligh
My application required to have switch case statement of type String
.
我的应用程序需要具有 type 的 switch case 语句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 withif
andelse
? Please comment on it?
编辑:
在
n
条件下使用 switch case而不是使用if
and会更好else
吗?请评论一下?
采纳答案by Vincent Ramdhanie
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.
}
回答by Brad Mace
See this question: Why can't I switch on a String?
看到这个问题:为什么我不能打开一个字符串?
Not currently supported, but expected to be in Java 7.
目前不支持,但预计在 Java 7 中。
Edit: actually appears to be String
s only, not any Object
s
编辑:实际上似乎只有String
s,而不是任何Object
s
Perhaps each object should implement a method that contains the logic you're trying to put into the switch statement?
也许每个对象都应该实现一个方法,该方法包含您试图放入 switch 语句的逻辑?
回答by Hovercraft Full Of Eels
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.
不,您不能这样做(尝试并找出答案)。但是如果你想要这个,也许像 HashMap 这样的 Map 更适合你的目的。
回答by Varun
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
不,使用 Hashmap 等其他集合或使用数组索引来做同样的事情,创建一个元素数组并在索引上放置一个 switch case
回答by gerdkolano
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
在 JDK 7 版本中,您可以在 switch 语句的表达式中使用 String 对象:http: //docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html
回答by Xiaogang
The switch can be supported for checking String, Integer and other primitive data types, but it is not approve successful in objects comparisons.
该开关可支持检查String、Integer等原始数据类型,但不批准对象比较成功。