如何使用“x< = y& amp;& x> = y&& x!= y"? [英] How to make loop infinite with "x <= y && x >= y && x != y"?

查看:104
本文介绍了如何使用“x< = y& amp;& x> = y&& x!= y"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几年前我有这个面试问题,但我还没有找到答案。

I had this interview question some years ago but I haven't found the answer yet.

x和y应该是什么才能产生无限循环?

What should be x and y to make a infinite loop?

while (x <= y&& x >= y && x != y) {

}

我们试过 Nan 无穷大+/- null

float vs int

推荐答案

您需要两个可比较的变量,具有相同的值,但代表不同的实例,例如:

You need two variables which are comparable, have the same value, but represent different instances, for example:

Integer x = new Integer(0);
Integer y = new Integer(0);

x< = y y< = x 都是true,因为 Integer 是未装箱的,但是实例相等 x = = y 为假。

x <= y and y <= x are both true because the Integer are unboxed, however the instance equality x == y is false.

请注意,它适用于 Float Double ,任何值(不只是0)都有效。

Note that it works with Float, Long and Double too, and any value (not just 0) works.

您还可以使用JVM的复杂性 - 它们通常只缓存最多127个整数,所以这也可以:

You can also play with the intricacies of your JVM - they generally cache integer up to 127 only, so this would work too:

Integer x = 128;
Integer y = 128;

(但不会是127)。

或者更简单,因为 Double s通常根本不缓存:

Or more simply, since Doubles are generally not cached at all:

Double x = 0d;
Double y = 0d;

这篇关于如何使用“x&lt; = y&amp; amp;&amp; x&gt; = y&amp;&amp; x!= y&quot;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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