使用列舉進行迭代的 Java 程式
在本文中,我們將瞭解如何對列舉物件進行迭代。列舉是一種表示一個較小物件集合的資料型別。
以下是示例 −
輸入
假設我們的輸入為 −
Enum objects are defined as : red, blue, green, yellow, orange
輸出
所需的輸出為 −
Printing the Objects: red blue green yellow orange
演算法
Step 1 – START Step 2 - Declare the objects of Enum function namely red, blue, green, yellow, orange Step 3 – Using a for loop, iterate over the objects of the enum function and print each object. Step 4- Stop
示例 1
enum Enum {
red, blue, green, yellow, orange;
}
public class Colour {
public static void main(String[] args) {
System.out.println("The values of Enum function are previously defined .");
System.out.println("Accessing each enum constants");
for(Enum colours : Enum.values()) {
System.out.print(colours + "\n");
}
}
}輸出
The values of Enum function are previously defined . Accessing each enum constants red blue green yellow orange
示例 2
以下是一個列印星期幾的示例。
import java.util.EnumSet;
enum Days {
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
public class IterateEnum{
public static void main(String args[]) {
Days my_days[] = Days.values();
System.out.println("Values of the enum are: ");
EnumSet.allOf(Days.class).forEach(day -> System.out.println(day));
}
}輸出
Values of the enum are: Sunday Monday Tuesday Wednesday Thursday Friday Saturday
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP