Saturday, December 24, 2016

What is the best code troll you've ever seen?

Consider the following Java snippet:
Integer a = 100, b = 100;
System.out.println(a == b);
Integer c = 200, d = 200;
System.out.println(c == d);


The first line will print true, and the second one will print false. This happens because Java has an autoboxing cache for Integers with a default range of [-128, 127]. Any value within that range will be reused from the cache.
Java Integer Cache - Java Tutorial Blog

Now, what if you mess with the cache and randomize it? Anyone doing arithmetic with Integer will have a really hard time understanding what the hell is going on!
// Extract the IntegerCache through reflection
    Class<?> clazz = Class.forName(
      "java.lang.Integer$IntegerCache");
    Field field = clazz.getDeclaredField("cache");
    field.setAccessible(true);
    Integer[] cache = (Integer[]) field.get(clazz);
 
    // Rewrite the Integer cache
    for (int i = 0; i < cache.length; i++) {
      cache[i] = new Integer(
        new Random().nextInt(cache.length));
    }
 
    // Prove randomness
    for (int i = 0; i < 10; i++) {
      System.out.println((Integer) i);
    }
  }

This code snippet were written by Lukas Eder on Add Some Entropy to Your JVM. For him, it printed this
92
221
45
48
236
183
39
193
33
84


Read other answers by Ruhul Quddus Shakkhor on Quora: Read more answers on Quora.

from Quora http://ift.tt/2icBr17

No comments:

Post a Comment