Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

java - How to make loop infinite with "x <= y && x >= y && x != y"?

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

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

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

}

We tried with Nan,infinity+/-,null

float vs int.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 and y <= x are both true because the Integer are unboxed, however the instance equality x == y is false.

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


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;

(but it would not with 127).

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...