java.lang.NullPointerException is thrown using a method-reference but not a lambda expression

This behaviour relies on a subtle difference between the evaluation process of method-references and lambda expressions. From the JLS Run-Time Evaluation of Method References: First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated. If the subexpression evaluates to null, a NullPointerException is raised, and the method reference … Read more

How do Java 8 array constructor references work?

You can find out yourself by decompiling the java bytecode: javap -c -v -p MyClass.class The compiler desugars array constructor references Foo[]::new to a lambda (i -> new Foo[i]), and then proceeds as with any other lambda or method reference. Here’s the disassembled bytecode of this synthetic lambda: private static java.lang.Object lambda$MR$new$new$635084e0$1(int); descriptor: (I)Ljava/lang/Object; flags: … Read more

Is method reference caching a good idea in Java 8?

You have to make a distinction between frequent executions of the same call-site, for stateless lambda or stateful lambdas, and frequent uses of a method-reference to the same method (by different call-sites). Look at the following examples: Runnable r1=null; for(int i=0; i<2; i++) { Runnable r2=System::gc; if(r1==null) r1=r2; else System.out.println(r1==r2? “shared”: “unshared”); } Here, the … Read more

Horrendous performance & large heap footprint of Java 8 constructor reference?

In the first case (ArrayList::new) you are using the constructor which takes an initial capacity argument, in the second case you are not. A large initial capacity (index in your code) causes a large Object[] to be allocated, resulting in your OutOfMemoryErrors. Here are the two constructors’ current implementations: public ArrayList(int initialCapacity) { if (initialCapacity … Read more

Java Pass Method as Parameter

Edit: as of Java 8, lambda expressions are a nice solution as other answers have pointed out. The answer below was written for Java 7 and earlier… Take a look at the command pattern. // NOTE: code not tested, but I believe this is valid java… public class CommandExample { public interface Command { public … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)