首页 » Web前端 » phpswitch字符串技巧_switch是若何实现支持字符串的

phpswitch字符串技巧_switch是若何实现支持字符串的

访客 2024-11-06 0

扫一扫用手机浏览

文章目录 [+]

我们来写一段大略的代码

public static void main(String[] args) { String sex = "male"; switch (sex) { case "male" : { System.out.println("男性"); break; } case "female" : { System.out.println("女性"); break; } default: { System.out.println("未知性别"); break; } }}

反编译这个类的class文件,我们可以看到,switch支持String的底层利用的是String的hashCode和equals方法

phpswitch字符串技巧_switch是若何实现支持字符串的

public static void main(String[] args) { String sex = "male"; byte var3 = -1; switch(sex.hashCode()) { case -1278174388: if (sex.equals("female")) { var3 = 1; } break; case 3343885: if (sex.equals("male")) { var3 = 0; } } switch(var3) { case 0: System.out.println("男性"); break; case 1: System.out.println("女性"); break; default: System.out.println("未知性别"); }}

phpswitch字符串技巧_switch是若何实现支持字符串的
(图片来自网络侵删)
标签:

相关文章