next和hasnext_使用Java中的next()和hasNext()方法遍历List元素
next和hasnext
Given a List of integers and we have to traverse, print all its element using next() and hasNext() methods.
給定一個整數(shù)列表,我們必須遍歷,使用next()和hasNext()方法打印其所有元素。
什么是hasNex()和next()方法? (What are hasNex() and next() methods?)
Both are the library methods of java.util.Scanner class.
兩者都是java.util.Scanner類的庫方法。
Method hasNext() returns 'true'/'false' - If collection has more values/elements, it returns true otherwise it returns false.
方法hasNext()返回'true'/'false'-如果collection具有更多的值/元素,則返回true,否則返回false 。
Method next() returns the next element in the collection.
方法next()返回集合中的下一個元素。
Note: In this example, we will create/declare an iterator by specifying Integer type - which is base type of the List and then the methods next() and hasNext() will be called through Iterator object.
注意:在此示例中,我們將通過指定Integer類型(這是List的基本類型)來創(chuàng)建/聲明一個迭代器,然后將通過Iterator對象調用 next()和hasNext()方法。
Example:
例:
In this example, we will declare a List of integers, add some of the elements and print the elements by using hasNext() and next() methods.
在此示例中,我們將聲明一個整數(shù)列表,添加一些元素,然后使用hasNext()和next()方法打印這些元素。
Program:
程序:
import java.util.*;public class ListExample {public static void main (String[] args) {//creating a list of integersList<Integer> int_list = new ArrayList<Integer> ();int count=0; //variable to count total traversed elements //adding some of the elementsint_list.add (10);int_list.add (20);int_list.add (30);int_list.add (40);int_list.add (50);//printing elementsSystem.out.println ("List elements are...");//creating iteratorIterator<Integer> it = int_list.iterator ();while (it.hasNext()){System.out.println (it.next());count+=1;}System.out.println ("Total traversed elements are: "+count);} };Output
輸出量
List elements are... 10 20 30 40 50 Total traversed elements are: 5翻譯自: https://www.includehelp.com/java-programs/traverse-the-list-elements-using-next-and-hasnext-methods-in-java.aspx
next和hasnext
總結
以上是生活随笔為你收集整理的next和hasnext_使用Java中的next()和hasNext()方法遍历List元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数组中的filter方法_数组filte
- 下一篇: ## c 连接字符_用于字符比较的C#程