📜  Java中的枚举 hasMoreElements() 方法及示例

📅  最后修改于: 2022-05-13 01:54:31.798000             🧑  作者: Mango

Java中的枚举 hasMoreElements() 方法及示例

实现Enumeration 接口的对象一次生成一系列元素。枚举hasMoreElements()方法用于测试此枚举是否包含更多元素。如果枚举包含更多元素,那么它将返回 true,否则返回 false。

句法:

boolean hasMoreElements()

参数:此方法不接受任何内容。

返回值:当且仅当此枚举对象包含至少一个要提供的元素时,此方法才返回 true;否则为假。

下面的程序说明了 hasMoreElements() 方法:
方案一:

// Java program to demonstrate
// Enumeration.hasMoreElements() method
  
import java.util.*;
  
public class GFG {
  
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args)
    {
  
        Enumeration Days;
        Vector week = new Vector();
  
        week.add("Sunday");
        week.add("Monday");
        week.add("Tuesday");
        week.add("Wednesday");
        week.add("Thursday");
        week.add("Friday");
        week.add("Saturday");
        Days = week.elements();
  
        while (Days.hasMoreElements()) {
            System.out.println("Day = "
                               + Days.nextElement());
        }
    }
}
输出:
Day = Sunday
Day = Monday
Day = Tuesday
Day = Wednesday
Day = Thursday
Day = Friday
Day = Saturday

方案二:

// Java program to demonstrate
// Enumeration.hasMoreElements() method
  
import java.util.*;
  
public class GFG {
  
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args)
    {
  
        Enumeration classNine;
        Vector rollno = new Vector();
  
        rollno.add(1);
        rollno.add(2);
        rollno.add(3);
        rollno.add(4);
        rollno.add(5);
        rollno.add(6);
        rollno.add(7);
        rollno.add(8);
        classNine = rollno.elements();
  
        while (classNine.hasMoreElements()) {
            System.out.println("Roll No = "
                               + classNine.nextElement());
        }
    }
}
输出:
Roll No = 1
Roll No = 2
Roll No = 3
Roll No = 4
Roll No = 5
Roll No = 6
Roll No = 7
Roll No = 8

参考资料: https: Java/util/Enumeration.html#hasMoreElements()