java集合中next()和hasNext()的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25397145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between next() and hasNext() in java collections
提问by coder
I am new to java and I was going through collections and during the iteration they have used next()
and hasNext()
methods. What exactly does these two methods do? When do I have to use next()
and hasNext()
?
我是 Java 新手,我正在浏览集合,并在迭代过程中使用了它们next()
和hasNext()
方法。这两种方法究竟有什么作用呢?我什么时候必须使用next()
and hasNext()
?
采纳答案by Raghu
hasNext()
will return true if iteration has more values and
next()
will return the next element in iteration
hasNext()
如果迭代有更多值,将返回 true 并将返回迭代中
next()
的下一个元素
回答by CloudyMarble
hasNext()- Returns true if the iteration has more elements.
hasNext()- 如果迭代有更多元素,则返回 true。
next()- Returns the next element in the iteration.
next()- 返回迭代中的下一个元素。
回答by jaimin
hasNext()
- "Returns true if the iteration has more elements"
So you can check if there are more objects you can get from the iterator, and if there are it returns true. If there are no more objects it will return false.
hasNext()
-“如果迭代有更多元素,则返回真”因此,您可以检查是否可以从迭代器中获取更多对象,如果有则返回真。如果没有更多对象,它将返回 false。
next()
- "Returns the next element in the iteration"
So if there is a next item, it will be returned. If there isn't it'll throw a 'NoSuchElementException', but if you use iterators properly you should never encounter it.
next()
- “返回迭代中的下一个元素” 所以如果有下一个项目,它将被返回。如果没有它会抛出一个“NoSuchElementException”,但如果你正确使用迭代器,你应该永远不会遇到它。
回答by Bhaumik Sathvara
hasNext(): hasNext() method returns true if iterator have more elements.
hasNext():如果迭代器有更多元素,hasNext() 方法返回 true。
next(): next() method returns the next element and also moves cursor pointer to the next element.
next(): next() 方法返回下一个元素并将光标指针移动到下一个元素。
回答by ashish rawat
HasNext() : if we are using hasNext() with the while loop for traversing in a collection then it returns a boolean value.
HasNext() :如果我们使用 hasNext() 和 while 循环遍历集合,则它返回一个布尔值。
hasNext() method check is there any element left in a row if yes then it returns true and if not then it returns false and the pointer goes out the loop.
hasNext() 方法检查是否有任何元素留在一行中,如果是,则返回 true,如果不是,则返回 false 并且指针退出循环。
while the next() method retruns the value of the next element in a row
而 next() 方法重新运行一行中的下一个元素的值