Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: How To Use Enums

  1. #1
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default How To Use Enums

    Hello all,

    This will be a little how to on the use of enums. I've seen a few questions pop up regarding these so I thought I'd write a little how to revealing some common methods etc for enums.

    It's important to remember that all the values that you declare in an enum are all instances of that enum. Complicated?

    If I create an enum called Day that holds the days of the week MONDAY to SUNDAY, calling Day.MONDAY actually returns an instance of the enum itself with the name of MONDAY.


    Methods
    These methods are all available on the enum without overriding or implementing them, these get explicitly inherited.

    String name()
    Returns the name of this enum constant, exactly as declared in its enum declaration.

    int ordinal()
    Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

    String toString()
    Returns the name of this enum constant, as contained in the declaration.

    <T> valueOf(String)
    Returns the enum who's name matches the input string.

    <T[]> values()
    Returns an array of all the enums values.


    Adding methods to an enum
    You can also add your own methods and constructors to an enum which I will show you how to do further down. This is useful if you for example would like to have an enum like the Day example which also gives you more information, such as for instance a boolean saying if this day is a weekend day or not.


    Example 1
    This creates the most simple form of enums, it only holds the values we define, with no extra methods.

        public enum Day {
            MONDAY,
            TUESDAY,
            WEDNESDAY,
            THURSDAY,
            FRIDAY,
            SATURDAY,
            SUNDAY;
        }


    Example 2
    This is the above enum created with some extra information. It holds a boolean telling us if the day is during a weekend or not. You can see that I've actually created two constructors here, one which takes no arguments and sets the weekend as default to false and another one which takes a boolean and sets the weekend value to whatever is passed in.

    When I then declare these enums I use the first constructor on MONDAY to FRIDAY as you can see below and on SATURDAY and SUNDAY I pass in a boolean of true to say that these two days are weekend days.

        public enum Day {
            MONDAY,
            TUESDAY,
            WEDNESDAY,
            THURSDAY,
            FRIDAY,
            SATURDAY(true),
            SUNDAY(true);
     
            private boolean weekend;
     
            private Day() {
                this.weekend = false;
            }
     
            private Day(final boolean weekend) {
                this.weekend = weekend;
            }
     
            public boolean isWeekend() {
                return weekend;
            }
        }

    This will let you check if the enum is a weekend day or not by calling the method isWeekend().

        final Day day = Day.SATURDAY;
        System.out.println(day.toString() + " is a weekend day is " + day.isWeekend());


    Conclusion
    This was a short how to on how to create enums, we've dealt with a most simple form of enums as well as adding extra methods, members and constructors.

    If there are still some question marks regarding enums please let us know and I'm sure either me or anyone else with some enum knowledge on these forums will answer your question.

    Enjoy! Happy coding!

    // Json

  2. The Following 2 Users Say Thank You to Json For This Useful Post:

    chronoz13 (October 15th, 2009), JavaPF (October 15th, 2009)


  3. #2
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: How To Use Enums

    thanks for this sample info sir Json.. more samples with this.Since you've taught me some little information about enums..(with the same samples) i've notice that. i can use enums in most of my programs... and this one gave me some big additional information!!

    regarding with the enum Day (public enum day)... is that an enum file?? not an ordinary instantiation of enum in a main program??

    same with defining a class?
    Last edited by chronoz13; October 15th, 2009 at 10:55 AM.

  4. #3
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How To Use Enums

    Glad you like it

    You can define enums as their own types if you wish just like a class so you could have Day.java which just has a public enum in it.

    // Json

  5. The Following User Says Thank You to Json For This Useful Post:

    chronoz13 (October 15th, 2009)

  6. #4
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: How To Use Enums

    and i also learned here that you can define more than one constructor for certain purposes ,
    one is for initializing the data members, and one for instantiation of an object.. or another one that accepts arguments.. this is one is a bit useful

  7. #5
    Junior Member
    Join Date
    Oct 2009
    Location
    Santa Cruz, CA
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How To Use Enums

    This is my first post to this forum. I'm sorry if this is not the appropriate place for this post. Please direct me to the correct location if it isn't.

    Here is my question: is it possible to iterate over an enum using the enhanced "for" loop?

    I am trying to implement a simple card game. A card would be an object that has a suit and a rank. I was thinking of using enums to implement the suits and ranks, something like:
    public enum cardSuits {
    	Spades,
    	Hearts,
    	Diamonds,
    	Clubs;
    }
     
    public enum cardRanks {
    	Ace,
    	King,
    	Queen,
    	...
    	Four,
    	Three,
    	Two;
    }
    I wanted to create the deck with enhanced "for" loops:
    card [] deck = new card[52];
    int i = 0;
    for (cardSuits suit : <suit iterable>) {
    	for (cardRanks rank : <rank iterable>) {
    		deck[i] = new Card();
    		deck[i].suit = suit;
    		deck[i].rank = rank;
    		i++;
    	}
    }
    Here are my questions:
    1) Is my approach feasible?

    2) If the answer to 1) is yes, what do I put into <suit iterable> and <rank iterable>?

    I think being able to iterate over an enum would be very useful. Thanks in advance.
    Last edited by helloworld922; October 20th, 2009 at 08:00 PM.

  8. #6
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How To Use Enums

    Well hello there and welcome, I must have missed that in my little post above, but yes you can iterate over the values of an enum.

    for(final Day day : Day.values()) {
        System.out.println(day.toString());
    }

    As you can see there you can use the Enum.values() method to get an array of the actual values in the enum.

    Enjoy!

    // Json

  9. #7
    Junior Member
    Join Date
    Oct 2009
    Location
    Santa Cruz, CA
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How To Use Enums

    Thanks, Json. I have a little background in Perl which has a foreach loop, but doesn't have enums. I knew there must a way to iterate over enums.

Similar Threads

  1. switch with Enums
    By chronoz13 in forum Loops & Control Statements
    Replies: 17
    Last Post: October 8th, 2009, 09:08 PM