一个选项是使用
Guava:
ImmutableList chars = Lists.charactersOf(someString);
UnmodifiableListIterator iter = chars.listIterator();
这将产生由给定字符串支持的不可变的字符列表(不涉及复制)。
如果你最终自己这样做,虽然,我建议不要公开实现类的Iterator作为一些其他的例子。我建议,而不是制作自己的实用程序类,并公开一个静态工厂方法:
public static Iterator stringIterator(final String string) {
// Ensure the error is found as soon as possible.
if (string == null)
throw new NullPointerException();
return new Iterator() {
private int index = 0;
public boolean hasNext() {
return index < string.length();
}
public Character next() {
/*
* Throw NoSuchElementException as defined by the Iterator contract,
* not IndexOutOfBoundsException.
*/
if (!hasNext())
throw new NoSuchElementException();
return string.charAt(index++);
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}