For loop - like Python range function

后端 未结 9 1516
情歌与酒
情歌与酒 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:40

    Its not available that true. But you make a static method and use it -

    public static int[] range(int index){
        int[] arr = new int[index];
        for(int i=0;i<index;i++){
            arr[i]=i;
        }
        return arr;
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-30 22:42

    Um... for (int i = 0; i < k; i++)? You don't have to write enhanced for loops all day, you know, although they are cool...

    And just for the sake of argument:

    for (int i : range(k)) char count: 22

    for (int i = 0; i < k; i++) char count: 27

    Discounting the implementation of range, it is pseudo even.

    0 讨论(0)
提交回复
热议问题