Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java switch语句支持string类型原理 #1890

Open
Joycepy opened this issue Jan 4, 2023 · 3 comments
Open

java switch语句支持string类型原理 #1890

Joycepy opened this issue Jan 4, 2023 · 3 comments

Comments

@Joycepy
Copy link

Joycepy commented Jan 4, 2023

switch语句支持string类型原理:在 https://javaguide.cn/java/basis/syntactic-sugar.html#switch-%E6%94%AF%E6%8C%81-string-%E4%B8%8E%E6%9E%9A%E4%B8%BE 这一章节中,反编译后的内容看起来会有哈希冲突的问题:如果本应该执行default语句,但遇到哈希冲突,就会出现执行结果错误。https://blog.csdn.net/acingdreamer/article/details/90765150 ,这篇文章中的解释(一个switch编译后会拆分为两个switch结构)看起来更合理。
但我试过在本地编译,使用 http://www.javadecompilers.com/ 进行反编译,得到的结果是

package test;

public class test
{
    public static void main(final String[] array) {
        final String s = "world";
        switch (s) {
            case "hello": {
                System.out.println("hello");
                break;
            }
            case "world": {
                System.out.println("world");
                break;
            }
        }
    }
}`

不太清楚为什么和网上的反编译结果不太一致

@Snailclimb
Copy link
Owner

Snailclimb commented Jan 5, 2023

https://blog.csdn.net/acingdreamer/article/details/90765150

推荐的这篇博客挺不错的👍不过,看了一下感觉还是挺奇怪的,没太懂为何又增加了一个 switch 。

@iosyyy
Copy link

iosyyy commented Mar 1, 2023

https://blog.csdn.net/acingdreamer/article/details/90765150

推荐的这篇博客挺不错的👍不过,看了一下感觉还是挺奇怪的,没太懂为何又增加了一个 switch 。

简单来说就是对于部分switch-case能实现的语法 if-else就没那么好实现了 尤其是在生成字节码文件的过程中可能会更复杂 所以图省事只是在判断的过程中使用if-else 实际上还是使用switch-case这样更好实现也会有更好的表现
ps:上面我自己意淫的 感觉应该是这个逻辑

@Reborn0s0
Copy link

牛逼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants