Created
March 28, 2010 16:28
-
-
Save VoQn/346846 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.ne.voqn.labs; | |
import java.util.Iterator; | |
/** | |
* <div> | |
* <p> | |
* like function of Python "range()".<br/> | |
* <code>>>> range(10)</code> <br/> | |
* returns <code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</code> <br/> | |
* (not contains <code>10</code>)<br/> | |
* </p> | |
* this class method "range" returns a Iterable Object | |
* </div> | |
* | |
* <h3>USASE</h3> | |
* <pre> | |
* import static jp.ne.voqn.labs.Range.*; | |
* | |
* public class AnimalSounds{ | |
* public static void main(String[] args){ | |
* String[] animals = { "cat", "dog", "big" }; | |
* String[] actionExp = {"is mewing", "is barking", "is saying"}; | |
* String[] sounds = {"\"meow\"", "\"bowwow\"", "\"oink, oink\""}; | |
* for(int i : range(animals.length){ | |
* Sytem.out.println(animals[i] + " " + sounds[i] + "."); | |
* } | |
* } | |
* } | |
* </pre> | |
* | |
* @author VoQn | |
*/ | |
public class Range implements Iterable<Integer> { | |
private static final String STEP_ARGUMENT_ERROR_MSG; | |
static{ | |
STEP_ARGUMENT_ERROR_MSG = "range() step argument must not be 0"; | |
} | |
private final int start, stop, step; | |
private Range(int start, int stop, int step) { | |
if(step == 0){ | |
throw new IllegalArgumentException(STEP_ARGUMENT_ERROR_MSG); | |
} | |
this.stop = stop; | |
this.step = step; | |
this.start = start; | |
} | |
private static int autoSign(final int start, final int stop){ | |
return stop < start ? -1 : 1; | |
} | |
public static Range range(int stop) { | |
return new Range(0, stop, autoSign(0, stop) * 1); | |
} | |
public static Range range(int start, int stop) { | |
return new Range(start, stop, autoSign(start, stop) * 1); | |
} | |
public static Range range(int start, int stop, int step) { | |
return new Range(start, stop, step); | |
} | |
public Iterator<Integer> iterator() { | |
return new Iterator<Integer>() { | |
private int current = start; | |
public boolean hasNext() { | |
return step < 0 ? current > stop : current < stop; | |
} | |
public Integer next() { | |
final int value = current; | |
current += step; | |
return value; | |
} | |
public void remove() { | |
throw new UnsupportedOperationException("Not supported yet."); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment