For loop - like Python range function

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

    If you really, really want to obtain an equivalent result in Java, you'll have to do some more work:

    public int[] range(int start, int end, int step) {
        int n = (int) Math.ceil((end-start)/(double)step);
        int[] arange = new int[n];
        for (int i = 0; i < n; i++)
            arange[i] = i*step+start;
        return arange;
    }
    

    Now range(0, 4, 1) will return the expected value, just like Python: [0, 1, 2, 3]. Sadly there isn't a simpler way in Java, it's not a very expressive language, like Python.

提交回复
热议问题