如何使用 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

更新於: 08-Feb-2021

361 次檢視

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.