การแจงนับใน Java แสดงถึงกลุ่มของค่าคงที่ที่มีชื่อ คุณสามารถสร้างการแจงนับโดยใช้รูปแบบต่อไปนี้ -
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
} คุณสามารถดึงเนื้อหาของ enum ได้โดยใช้วิธี values() เมธอดนี้ส่งคืนอาร์เรย์ที่มีค่าทั้งหมด เมื่อคุณได้อาร์เรย์มาแล้ว คุณสามารถทำซ้ำได้โดยใช้ for loop
ตัวอย่าง
public class IterateEnum{
public static void main(String args[]) {
Days days[] = Days.values();
System.out.println("Contents of the enum are: ");
//Iterating enum using the for loop
for(Days day: days) {
System.out.println(day);
}
}
} ผลลัพธ์
Contents of the enum are: SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
ตัวอย่าง
enum Vehicles {
//Declaring the constants of the enum
ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
int i; //Instance variable
Vehicles() { //constructor
}
public void enumMethod() { //method
System.out.println("Current value: "+Vehicles.this);
}
}
public class Sam{
public static void main(String args[]) {
Vehicles vehicles[] = Vehicles.values();
for(Vehicles veh: vehicles) {
System.out.println(veh);
}
vehicles[3].enumMethod();
}
} ผลลัพธ์
ACTIVA125 ACTIVA5G ACCESS125 VESPA TVSJUPITER Current value: VESPA