For loop - like Python range function

后端 未结 9 1576
情歌与酒
情歌与酒 2020-12-30 21:45

I was wondering if in Java there is a function like the python range function.

range(4)

and it would return

[0,1,2,3]
         


        
9条回答
  •  星月不相逢
    2020-12-30 22:41

    There's no Java equivalent to the range function, but there is an enhanced for-loop:

    for (String s : strings) {
        // Do stuff
    }
    

    You could also roll your own range function, if you're really attached to the syntax, but it seems a little silly.

    public static int[] range(int length) {
        int[] r = new int[length];
        for (int i = 0; i < length; i++) {
            r[i] = i;
        }
        return r;
    }
    
    // ...
    
    String s;
    for (int i : range(arrayOfStrings.length)) {
        s = arrayOfStrings[i];
        // Do stuff
    }
    

提交回复
热议问题