我需要一个 Iterator<Character>
来自 String
目的。 Java 中是否有任何可用函数可以为我提供此功能,还是我必须自己编写代码?
最佳答案
一种选择是使用 Guava :
ImmutableList<Character> chars = Lists.charactersOf(someString);
UnmodifiableListIterator<Character> iter = chars.listIterator();
这会生成一个由给定字符串支持的不可变字符列表(不涉及复制)。
如果您最终自己这样做,我建议不要像许多其他示例那样公开 Iterator
的实现类。我建议改为创建自己的实用程序类并公开静态工厂方法:
public static Iterator<Character> stringIterator(final String string) {
// Ensure the error is found as soon as possible.
if (string == null)
throw new NullPointerException();
return new Iterator<Character>() {
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();
}
};
}
关于Java:如何从字符串中获取 Iterator<Character>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3925130/