Can (a==1 && a==2 && a==3) evaluate to true in Java?

后端 未结 8 744
梦如初夏
梦如初夏 2020-11-29 15:01

We know it can in JavaScript.

But is it possible to print \"Success\" message on the condition given below in Java?

if (a==1 && a==2 &&am         


        
8条回答
  •  生来不讨喜
    2020-11-29 15:41

    Using concepts (and code) from a brilliant code golf answer, Integer values can be messed with.

    In this case, it can make ints casted to Integers be equal when they wouldn't normally be:

    import java.lang.reflect.Field;
    
    public class Test
    {
        public static void main(String[] args) throws Exception
        {
            Class cache = Integer.class.getDeclaredClasses()[0];
            Field c = cache.getDeclaredField("cache");
            c.setAccessible(true);
            Integer[] array = (Integer[]) c.get(cache);
            // array[129] is 1
            array[130] = array[129]; // Set 2 to be 1
            array[131] = array[129]; // Set 3 to be 1
    
            Integer a = 1;
            if(a == (Integer)1 && a == (Integer)2 && a == (Integer)3)
                System.out.println("Success");
        }
    }
    

    Unfortunately it's not quite as elegant as Erwin Bolwidt's multithreaded answer (as this one requires Integer casting), but still some fun shenanigans take place.

提交回复
热议问题