java中可以有switch(java.lang.Object)吗?
我的应用程序需要具有 String
类型的 switch case 语句。
我需要这样的东西:
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
}
有可能吗?
编辑:
对于
n
条件使用 switch case 比使用if
更好吗? 还有其他
?请评论一下?
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 withif
andelse
? Please comment on it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于您要打开字符串,我假设字符串在编译时是已知的。在这种情况下,您可以使用枚举。
然后
Since you are switching on Strings I assume that the strings are known at compile time. In that case you can use an enum.
Then
在 JDK 7 版本中,您可以在 switch 语句的表达式中使用 String 对象:
http://docs.oracle.com/javase /7/docs/technotes/guides/language/strings-switch.html
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
请参阅此问题:为什么我无法打开字符串?
目前不行支持,但预计在 Java 7 中。
编辑:实际上似乎只是
String
,而不是任何Object
也许每个对象都应该实现一个包含您的逻辑的方法正在尝试放入 switch 语句中?
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
String
s only, not anyObject
sPerhaps each object should implement a method that contains the logic you're trying to put into the switch statement?
不,你不能这样做(尝试一下就知道了)。但如果你想要这个,也许像 HashMap 这样的 Map 更适合你的目的。
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)或使用数组索引来执行相同的操作,创建元素数组并在索引上放置 switch case
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
该开关可以支持检查 String、Integer 等原始数据类型,但在对象比较中不支持成功。
The switch can be supported for checking String, Integer and other primitive data types, but it is not approve successful in objects comparisons.