Wouldn't this be nice?

David Schlosnagle schlosna at gmail.com
Wed Nov 11 10:25:14 PST 2009


I haven't searched through Guava enough yet to see if there is
something similar already, but I'd imagine it would easy to define
static methods that return an Iterable of the desired type, for
example the following to iterate over the characters in a
CharSequence. The same could be done to abstract code point iteration.

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Characters {

    public static void main(String[] args) {
        for (char c : characters("hello, world")) {
            System.out.println(c);
        }
    }

    public static Iterable<Character> characters(final CharSequence sequence) {
        return new Iterable<Character>() {

            public Iterator<Character> iterator() {
                return new Iterator<Character>() {

                    private int index = 0;

                    public boolean hasNext() {
                        return index < sequence.length();
                    }

                    public Character next() {
                        if (hasNext())
                            return sequence.charAt(index++);
                        throw new NoSuchElementException();
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
}


On Wed, Nov 11, 2009 at 1:00 PM, Bob Lee <crazybob at crazybob.org> wrote:
> On Wed, Nov 11, 2009 at 9:37 AM, Reinier Zwitserloot <
> reinier at zwitserloot.com> wrote:
>
>> Josh: I'm a bit meh on your suggestion. Is that really so much of an
>> improvement over:
>>
>> for (char c : "someString".toCharArray())?
>
>
> Yes. I would never use your suggestion because it results in an extra array
> copy.
>
> Bob
>
>



More information about the coin-dev mailing list