| 
2 | 2 | // (c)2021 MindView LLC: see Copyright.txt  | 
3 | 3 | // We make no guarantees that this code is fit for any purpose.  | 
4 | 4 | // Visit http://OnJava8.com for more book information.  | 
5 |  | -// Array creation methods that can be used without  | 
6 |  | -// qualifiers, using static imports:  | 
 | 5 | +// Create arrays initialized with integer values.  | 
7 | 6 | package onjava;  | 
8 | 7 | 
 
  | 
9 | 8 | public class Range {  | 
10 |  | -  // Produce a sequence [0..n)  | 
11 |  | -  public static int[] range(int n) {  | 
12 |  | -    int[] result = new int[n];  | 
13 |  | -    for(int i = 0; i < n; i++)  | 
14 |  | -      result[i] = i;  | 
15 |  | -    return result;  | 
16 |  | -  }  | 
17 |  | -  // Produce a sequence [start..end)  | 
18 |  | -  public static int[] range(int start, int end) {  | 
19 |  | -    int sz = end - start;  | 
20 |  | -    int[] result = new int[sz];  | 
21 |  | -    for(int i = 0; i < sz; i++)  | 
22 |  | -      result[i] = start + i;  | 
23 |  | -    return result;  | 
24 |  | -  }  | 
25 | 9 |   // Produce sequence [start..end) incrementing by step  | 
26 | 10 |   public static  | 
27 | 11 |   int[] range(int start, int end, int step) {  | 
28 |  | -    int sz = (end - start)/step;  | 
 | 12 | +    if (step == 0)  | 
 | 13 | +      throw new  | 
 | 14 | +        IllegalArgumentException("Step cannot be zero");  | 
 | 15 | +    int sz = Math.max(0, step >= 0 ?  | 
 | 16 | +        (end + step - 1 - start) / step  | 
 | 17 | +      : (end + step + 1 - start) / step);  | 
29 | 18 |     int[] result = new int[sz];  | 
30 | 19 |     for(int i = 0; i < sz; i++)  | 
31 | 20 |       result[i] = start + (i * step);  | 
32 | 21 |     return result;  | 
 | 22 | +  }  // Produce a sequence [start..end)  | 
 | 23 | +  public static int[] range(int start, int end) {  | 
 | 24 | +    return range(start, end, 1);  | 
 | 25 | +  }  | 
 | 26 | +  // Produce a sequence [0..n)  | 
 | 27 | +  public static int[] range(int n) {  | 
 | 28 | +    return range(0, n);  | 
33 | 29 |   }  | 
34 | 30 | }  | 
0 commit comments