How to make loop infinite with “x <= y && x >= y && x != y”?

前端 未结 4 815
南方客
南方客 2020-12-16 11:07

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&am         


        
相关标签:
4条回答
  • 2020-12-16 11:38

    you have to create two Integer Objects, for example:

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

    Because x and y are Objects and no ordinal types, you get an infinite loop.

    0 讨论(0)
  • 2020-12-16 11:45

    Here it is.

    Integer x =1;
    Integer y = new Integer(1);
    while(x <= y&& x >= y && x != y) {
        System.out.println("Success");
    }
    
    0 讨论(0)
  • 2020-12-16 11:47

    You've got your answer, I just wanted to say how I got to the same one. In the normal world such a test would be useless, there is no way for two number to work like that. So that means it HAS to be some java specific.

    x and y could be either simple types - which makes it impossible right away.

    x and y could be objects. But what objects are compared with <= or >=? Only 'boxed' numbers. Thus the answer comes up really fast.

    0 讨论(0)
  • 2020-12-16 11:55

    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;
    
    0 讨论(0)
提交回复
热议问题