A final counter in a for loop?

后端 未结 6 887
滥情空心
滥情空心 2020-12-03 21:07

I have this code:

    List r = new ArrayList<>();
    for(int i = 0; i < 10; i++) {
        r.add(new Runnable() {

            @Ove         


        
6条回答
  •  旧巷少年郎
    2020-12-03 21:42

    I think your solution is the simplest way.

    Another option would be to refactor the creation of the inner class into a factory function that does it for you, then your loop itself could be something clean like:

    List r = new ArrayList<>();
    for(int i = 0; i < 10; i++) {
        r.add(generateRunnablePrinter(i));
    }
    

    And the factory function could just declare a final parameter:

    private Runnable generateRunnablePrinter(final int value) {
        return new Runnable() {
           public void run() {
               System.out.println(value);
           }
        };
    }
    

    I prefer this refactored approach because it keeps the code cleaner, is relatively self descriptive and also hides away all the inner class plumbing.

    Random digression: if you consider anonymous inner classes to be equivalent to closures, then generateRunnablePrinter is effectively a higher order function. Who said you can't do functional programming in Java :-)

提交回复
热议问题