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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:25:18  来源:igfitidea点击:

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

javaobjectswitch-statementif-statement

提问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 nconditions rather going with ifand else? Please comment on it?

编辑:

n条件下使用 switch case而不是使用ifand会更好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 Strings only, not any Objects

编辑:实际上似乎只有Strings,而不是任何Objects

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等原始数据类型,但不批准对象比较成功。