How can I write an anonymous function in Java?

后端 未结 5 1196
无人及你
无人及你 2020-12-22 23:15

Is it even possible?

5条回答
  •  太阳男子
    2020-12-22 23:59

    Here's an example of an anonymous inner class.

    System.out.println(new Object() {
        @Override public String toString() {
            return "Hello world!";
        }
    }); // prints "Hello world!"
    

    This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.

    See also

    • JLS 15.9.5 Anonymous Class Declarations

    Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator for sorting.

    Here's an example of how you can sort a String[] based on String.length().

    import java.util.*;
    //...
    
    String[] arr = { "xxx", "cd", "ab", "z" };
    Arrays.sort(arr, new Comparator() {
        @Override public int compare(String s1, String s2) {
            return s1.length() - s2.length();
        }           
    });
    System.out.println(Arrays.toString(arr));
    // prints "[z, cd, ab, xxx]"
    

    Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).

    See also

    • Java Integer: what is faster comparison or subtraction?
      • Comparison-by-subtraction is broken in general
    • Create a Sorted Hash in Java with a Custom Comparator
    • How are Anonymous (inner) classes used in Java?

提交回复
热议问题