Skip to content

Instantly share code, notes, and snippets.

@j5ik2o j5ik2o/gist:970362
Created May 13, 2011

Embed
What would you like to do?
JavaでRangeオブジェクト的ななにか
package util;
import java.io.Serializable;
import java.util.Iterator;
public class Range implements Iterable<Integer>, Serializable, Cloneable {
private static class RangeIterator implements Iterator<Integer> {
final int start;
final int end;
final int interval;
int current;
RangeIterator(int start, int end, int interval) {
this.start = start;
this.end = end;
this.interval = interval;
current = start;
}
@Override
public boolean hasNext() {
return current <= end;
}
@Override
public Integer next() {
final int ret = current;
current += interval;
return Integer.valueOf(ret);
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
public static Range range(final int end) {
return new Range(0, end, 1);
}
public static Range range(final int start, final int end) {
return new Range(start, end, 1);
}
public static Range range(final int start, final int end, final int interval) {
return new Range(start, end, interval);
}
private final int start;
private final int end;
private int interval;
Range(final int start, final int end, final int interval) {
this.start = start;
this.end = end;
this.interval = interval;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public Iterator<Integer> iterator() {
return new RangeIterator(start, end, interval);
}
public Range withInterval(final int interval) {
try {
Range clone = (Range) clone();
clone.interval = interval;
return clone;
} catch (CloneNotSupportedException ex) {
throw new RuntimeException(ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.