JavaJAVA7新特性之放宽switch的应用范围

在Java7发表之后,关于switch的用法上,除了char,byte,short,int之外,允许了String。例如(不得以为null):

public class Title {

    public static String generate(String name,String gender){
        String title = "";
        switch (gender){
        case "男":
            title = name + "先生";
            break;
        case "女":
            title = name + "女士";
            break;
        default:
            title = name;
            break;
        }
        return title;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(Title.generate("林嘉瑜","男"));
    }

}

case显著是无法重复的,例如下边这一个事例就出错

public class TitleDuplicate {

    public static String generate(String name,String gender){
        String title = "";
        switch (gender){
        case "男":
            title = name + "先生";
            break;
        case "\u7537":
            title = name + "女士";
            break;
        default:
            title = name;
            break;
        }
        return title;
    }

}

因为\u7537转换之后实际也是男。

相关文章