1

Is there a difference between these lines of code, and what is best to use it? thanks

public static void main( String[] args ){
   SwingUtilities.invokeLater( () -> component.method() ); }

vs

public static void main( String[] args ) {
   SwingUtilities.invokeLater( new Runnable() {
      public void run(){
            component.method();
    }} );
}

or

public static void main( String[] args ) {
   SwingUtilities.invokeLater( new Runnable() {
      public void run(){
            component::method();
    }} );
}
byte
  • 112
  • 7
  • 6
    The third one won't compile. – khelwood Sep 17 '18 at 06:11
  • There are differences, yes. But the last one will not compile (should probably be `invokeLater(component::method);`) – ernest_k Sep 17 '18 at 06:12
  • For the first two read this: https://alvinalexander.com/java/java-8-lambda-thread-runnable-syntax-examples For the last one, read this: https://stackoverflow.com/questions/20001427/double-colon-operator-in-java-8 – Pedreiro Sep 17 '18 at 06:16
  • Only difference between method invocation inside lambda function and direct method reference is a one more line in a StackTrace. – SHaaD Sep 17 '18 at 06:17

1 Answers1

4

The last one doesn't pass compilation.

Using either lambda expression

SwingUtilities.invokeLater(() -> component.method());

or method reference

SwingUtilities.invokeLater(component::method);

is shorter than the second one, which makes them preferable in Java 8 and later.

Eran
  • 387,369
  • 54
  • 702
  • 768