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

随机的int有问题 #68

Closed
oweson opened this issue Nov 14, 2019 · 2 comments
Closed

随机的int有问题 #68

oweson opened this issue Nov 14, 2019 · 2 comments
Assignees
Labels

Comments

@oweson
Copy link

oweson commented Nov 14, 2019

这条其实是一个迷题,先不要看解答。看看你能不能自己找出解法。

运行下面的代码:

for (int i = 0; i < 10; i++) {
    System.out.println((Integer) i);
}

…… 然后要得到类似下面的输出(每次输出是随机结果):

92
221
45
48
236
183
39
193
33
84

Output:

0
1
2
3
4
5
6
7
8
9
@cmonkey
Copy link

cmonkey commented Nov 14, 2019

直接运行上面的代码当然不会出问题,关键在于在完整实现中,通过反射调用Integer#IntegerCache 对cache 中的数据进行了随机篡改,最后才导致读取cache 中的值不符合未修改cache 时的预期

在jdk 8 版本上,编译和运行都不会告警,但在高版本的jdk 上在编译阶段就会警告,比如在jdk 13 上就会警告说对IntegerCache 的反射不合法,在未来此api 可能会被删除

@oldratlee
Copy link
Owner

oldratlee commented Nov 18, 2019

@oweson

@cmonkey 所言,这是个谜题,

要你写出解法(即,关键在于在完整实现中,通过反射调用Integer#IntegerCachecache中的数据进行了随机篡改,最后才导致读取cache 中的值不符合未修改cache 时的预期),

让上面的代码运行成 随机的。

@oldratlee oldratlee self-assigned this Dec 3, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants