Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Asgeir S. Nilsen http://www.asgeirnilsen.com/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Handy Iterable for a range of Integers

Looping a specific number of times produces code a bit too verbose in Java. The JDK5 enhanced for statement is a handy improvement, but you still have to fall back to the traditional for statement if you want to repeat a loop, say, 10 times.

Not with this implementation of Iterable. You can use it like this:

   1  
   2  for (int i : new Range(100))
   3      System.out.printf("I have said this %d times. Read dzone.com!%n", i);
   4  
   5  class Range implements Iterable<Integer> {
   6      
   7      private final Integer stop;
   8      
   9      public Range(int stop) {
  10          this.stop = stop;
  11      }
  12  
  13      public Iterator<Integer> iterator() {
  14          return new Iterator<Integer>() {
  15              
  16              private Integer counter = 0;
  17  
  18              public boolean hasNext() {
  19                  return (counter != stop);
  20              }
  21  
  22              public Integer next() {
  23                  if (counter == stop)
  24                      throw new NoSuchElementException();
  25                  return ++counter;
  26              }
  27  
  28              public void remove() {
  29              }};
  30      }
  31      
  32  }
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS