java编程思想_008产生指定数组类

package wzs.test2;

import java.util.Arrays;

//产生指定数组类
public class Test
{
    public static void main(String[] args)
    {
        int[] a1 = rang(10);
        int[] a2 = rang(2, 10);
        int[] a3 = rang(2, 10, 2);
        System.out.println("a1:" + Arrays.toString(a1));
        System.out.println("a2:" + Arrays.toString(a2));
        System.out.println("a3:" + Arrays.toString(a3));
    }

    /**
     * 0 -- n
     * @param n
     * @return
     */
    public static int[] rang(int n)
    {
        int[] result = new int[n];
        for (int i = 0; i < n; i++)
        {
            result[i] = i;
        }
        return result;
    }

    /**
     * start -- end
     * @param start
     * @param end
     * @return
     */
    public static int[] rang(int start, int end)
    {
        int size = end - start;
        int[] result = new int[size];
        for (int i = 0; i < size; i++)
        {
            result[i] = start + i;
        }
        return result;
    }

    /**
     * start -- end 步长为step
     * @param start
     * @param end
     * @param step
     * @return
     */
    public static int[] rang(int start, int end, int step)
    {
        int size = (end - start) / step;
        int[] result = new int[size];
        for (int i = 0; i < size; i++)
        {
            result[i] = start + i * step;
        }
        return result;
    }
}

输出结果:

a1:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a2:[2, 3, 4, 5, 6, 7, 8, 9]
a3:[2, 4, 6, 8]


你可能感兴趣的:(java,java,java,java编程思想,java编程思想,java经典书籍)