1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.apache.commons.functor.generator.util;
16
17 import org.apache.commons.functor.UnaryProcedure;
18 import org.apache.commons.functor.generator.BaseGenerator;
19
20
21
22
23
24
25
26
27
28
29 public final class IntegerRange extends BaseGenerator<Integer> {
30
31
32
33 private final int from;
34 private final int to;
35 private final int step;
36
37
38
39
40
41
42
43
44 public IntegerRange(Number from, Number to) {
45 this(from.intValue(), to.intValue());
46 }
47
48
49
50
51
52
53
54 public IntegerRange(Number from, Number to, Number step) {
55 this(from.intValue(), to.intValue(), step.intValue());
56 }
57
58
59
60
61
62
63 public IntegerRange(int from, int to) {
64 this(from, to, defaultStep(from, to));
65 }
66
67
68
69
70
71
72
73 public IntegerRange(int from, int to, int step) {
74 if (from != to && signOf(step) != signOf(to - from)) {
75 throw new IllegalArgumentException("Will never reach " + to + " from " + from + " using step " + step);
76 }
77 this.from = from;
78 this.to = to;
79 this.step = step;
80 }
81
82
83
84
85
86
87 public void run(UnaryProcedure<? super Integer> proc) {
88 if (signOf(step) == -1) {
89 for (int i = from; i > to; i += step) {
90 proc.run(i);
91 }
92 } else {
93 for (int i = from; i < to; i += step) {
94 proc.run(i);
95 }
96 }
97 }
98
99
100
101
102 public String toString() {
103 return "IntegerRange<" + from + "," + to + "," + step + ">";
104 }
105
106
107
108
109 public boolean equals(Object obj) {
110 if (obj == this) {
111 return true;
112 }
113 if (!(obj instanceof IntegerRange)) {
114 return false;
115 }
116 IntegerRange that = (IntegerRange) obj;
117 return this.from == that.from && this.to == that.to && this.step == that.step;
118 }
119
120
121
122
123 public int hashCode() {
124 int hash = "IntegerRange".hashCode();
125 hash <<= 2;
126 hash ^= from;
127 hash <<= 2;
128 hash ^= to;
129 hash <<= 2;
130 hash ^= step;
131 return hash;
132 }
133
134
135
136
137
138
139
140
141 private static int signOf(int value) {
142 return value < 0 ? -1 : value > 0 ? 1 : 0;
143 }
144
145
146
147
148
149
150
151 private static int defaultStep(int from, int to) {
152 return from > to ? -1 : 1;
153 }
154
155 }