ในบทความนี้ เราจะเข้าใจวิธีการวนซ้ำวัตถุ enum Enum เป็นประเภทข้อมูลที่แสดงถึงคอลเล็กชันของอ็อบเจ็กต์ขนาดเล็ก
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
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