for循环在比较Integer.MAX_VALUE和使用System.out.println时提前终止 [英] for loop terminating early when comparing to Integer.MAX_VALUE and using System.out.println

查看:223
本文介绍了for循环在比较Integer.MAX_VALUE和使用System.out.println时提前终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行这个类的时候,for循环似乎很快就终止了

  class Test {

public static void main(String [] args){
int result = 0;
int end = Integer.MAX_VALUE;
int i; (i = 1; i< = end; i + = 2)
System.out.println(i);
}
System.out.println(End:+ i);
}

}

输出结果是:

  1 
3
5
...
31173
31175
结尾:31177

为什么结束?有趣的是,如果我在for循环中删除了 System.out.println(i),输出将是结束:-2147483647 。很明显, i 中的值包含> 。

我正在使用的Java版本是

pre $ Java $ SE运行时环境(build 1.6.0_16-b01)
Java HotSpot(TM)64位服务器虚拟机(构建14.2-b01,混合模式)


解决方案

它是Java 6中的一个已知错误.JIT错误地优化了循环。我相信更新的Java版本没有这个bug。

http://vanillajava.blogspot.co.uk/2011/05/when-jit-gets-it-wrong.html



Java 6 update 16已经过了两年多了。我建议你更新到最新版本的Java 6更新25,如果你不能更新到Java 7.



顺便提一下,Java 6将是免费支持个月(2012年12月)

When I run this class the for loop seems to terminate early

class Test {

    public static void main(String[] args) {
        int result = 0;
        int end = Integer.MAX_VALUE;
        int i;
        for (i = 1; i <= end; i += 2) {
            System.out.println(i);
        }
        System.out.println("End:" + i);
    }

}

Output is:

1
3
5
...
31173
31175
End:31177

Why does it end there? Interestingly if I removed the System.out.println(i) in the for loop, the output would be End:-2147483647. Obviously the value in i has wrapped round.

The Java version I'm using is

Java(TM) SE Runtime Environment (build 1.6.0_16-b01)
Java HotSpot(TM) 64-Bit Server VM (build 14.2-b01, mixed mode)

解决方案

Its a known bug in Java 6. The JIT optimizes the loop incorrectly. I believe more recent versions of Java don't have this bug.

http://vanillajava.blogspot.co.uk/2011/05/when-jit-gets-it-wrong.html

Java 6 update 16 is just over two years old. I suggest you update to the latest version Java 6 update 25 if you can't update to Java 7.

BTW Java 6 will be End Of Free Support in a couple of months (Dec 2012)

这篇关于for循环在比较Integer.MAX_VALUE和使用System.out.println时提前终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆