суббота, 18 февраля 2017 г.

Java 8: Integer

Everyone knows that Java has boxing functionality:
 Integer one = 4;
 Integer two = 4;
 Assert.assertTrue(one==two);

 Integer $600 = 600;
 Integer also600 = 600;
 Assert.assertTrue($600 != also600);


It works as written in JLS (http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.7).
This is due to the caching functionality inside the Integer class and the method Integer.valueOf which is used by boxing.

What's more we can make the second test pass. Cache inside Integer can be tuned by passing  system property -Djava.lang.Integer.IntegerCache.high=600 to the JVM. The bad thing is that low bound of Integer cache cannot be tuned.

Another example is:
 Integer $4 = new Integer(4);
 Integer $anotherInstance = 4;
 Assert.assertTrue($anotherInstance!=$4);

This is because new Integer(4) bypasses the cache.  Why? Is it a good design?
Is it the premature optimization evil?
Interesting case that other wrapper classes also contain the caching functionality, but only Integer class has the possibility to tune the size of the cache.

One more thing: do we actually need Integer constructor which accepts String if the same goal can be achieved with Integer.valueOf method?

Комментариев нет:

Отправить комментарий