Can Java store methods in arrays?

后端 未结 5 2158
生来不讨喜
生来不讨喜 2020-12-31 08:55

Well I wrote some code and all I was doing was for loops, but changing which method I called. I tried using a for loop so it\'d be a bit neater (and out of curiosity to see

5条回答
  •  猫巷女王i
    2020-12-31 09:26

    Updated answer for Java 8 and onwards-

    Since the introduction of lambda expressions and method references in Java 8, storing various methods in variables is now possible. One main issue is that arrays don't currently support generic objects in Java, which makes storing the methods in arrays less doable. However they can be stored in other data structures like a List.

    So for some simple examples you can write something like:

    List> stringComparators = new ArrayList<>();
    Comparator comp1 = (s1, s2) -> Integer.compare(s1.length(), s2.length());
    stringComparators.add(comp1);
    

    or

    List> consumers = new ArrayList<>();
    Consumer consumer1 = System.out::println;
    consumers.add(consumer1);
    

    and then loop/iterate through the List to get the methods.

提交回复
热议问题