Created
June 9, 2014 12:11
-
-
Save ShinNoNoir/82a9c6e49264301ec213 to your computer and use it in GitHub Desktop.
Simple example demonstrating how Java can close over (final) variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.ArrayList; | |
| import java.util.List; | |
| public class ClosureExample { | |
| public static void main(String[] args) { | |
| List<Runnable> actions = new ArrayList<>(); | |
| for (int i = 0; i < 10; i++) { | |
| final int j = i; | |
| actions.add(new Runnable() { | |
| public void run() { | |
| System.out.println("Captured: " + j); | |
| } | |
| }); | |
| } | |
| for (Runnable action : actions) { | |
| action.run(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment