我是靠谱客的博主 背后小鸽子,这篇文章主要介绍java string iterator_Java:如何从String获取Iterator,现在分享给大家,希望可以做个参考。

一种选择是使用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();

}

};

}

最后

以上就是背后小鸽子最近收集整理的关于java string iterator_Java:如何从String获取Iterator的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部