Results 1 to 2 of 2

Thread: Enum Iteration

  1. #1
    A.Russell is offline Member
    Join Date
    Aug 2007
    Rep Power

    Default Enum Iteration

    How do you iterate through an enumeration in Java? I tried the way I would expect from working with C++:

    Java Code:
    for( int ix = 1; ix < MyEnum.LastEnum; ix++)
      // Do something here
    I get the error "Cannot cast MyEnum to Int." Isn't an enumeration always a constant integral type? If not, how can I iterate through enumerations?

  2. #2
    shanePreater is offline Member
    Join Date
    Jul 2007
    England, Bath
    Rep Power


    An Enum is strongly typed so, unlike c++, you can't implicitly cast from an enum to an int and vice versa.
    To do your loop using the values() static function to get an array of MyEnum objects:
    Java Code:
    for(MyEnum myEnum : MyEnum.values()) {
    			//Do stuff here!
    Hope that sorts you out,

Similar Threads

  1. Constructor with enum
    By bugger in forum New To Java
    Replies: 2
    Last Post: 01-04-2008, 11:21 AM
  2. enum to array
    By eva in forum New To Java
    Replies: 2
    Last Post: 12-22-2007, 06:50 PM
  3. iteration on huge amount of files in a folder
    By tshaked in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 07:08 PM
  4. Enum?
    By vgbhagavan in forum Advanced Java
    Replies: 0
    Last Post: 06-14-2007, 02:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts