A final counter in a for loop?

后端 未结 6 884
滥情空心
滥情空心 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条回答
  •  -上瘾入骨i
    2020-12-03 21:51

    (Less-than optimal) alternative: create a small inner class that implements Runnable:

    class Printer implements Runnable {
        private int index;
    
        public Printer(int index) {
            this.index = index;
        }
    
        public void run() {
            System.out.println(index);
        }
    }
    
    List r = new ArrayList<>();
    for(int i = 0; i < 10; i++) {
        r.add(new Printer(i));
    }
    

提交回复
热议问题