如何使用 Java 中的 for 迴圈迭代列舉的值?
Java 中的列舉表示一組已命名常量,你可以使用以下語法建立一個列舉 −
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}你可以使用 values() 方法檢索列舉的內容。此方法返回一個包含所有值的陣列。獲得陣列後,可以使用 for 迴圈對其進行迭代。
示例
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP