aspose file tools*
The moose likes Beginning Java and the fly likes Getting a random element from an Enum Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getting a random element from an Enum" Watch "Getting a random element from an Enum" New topic
Author

Getting a random element from an Enum

Cate van Alphen
Greenhorn

Joined: Jun 16, 2006
Posts: 16
Hi,

What I am trying to do is get a random element out of an enum, the array equivalent is:


I found enum has an ordinal() function that returns its position in its enum declaration, but I can't figure out how to get an object out using the position. The best I've come up with is this, given an enum called Season:



which seems terribly clunky, I wondered if there was an easier way.
James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

Given an enum say
enum X {a,b,c,d,e,f}
then



Retired horse trader.
 Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Cate van Alphen
Greenhorn

Joined: Jun 16, 2006
Posts: 16
Thanks. I'm a bit confused about where the .values() comes from. In the api I can find an abstract class Enum, but you declare an enum, is this different, and if so where do I find info about it? Is X.values() an array of the enum X?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14266
    
  21

Every enum has an automatically generated values() method that returns all the enum values in an array. You won't find it in class Enum<E extends Enum<E>> - the compiler just automatically generates it. Note that the values() method of an enum type is static.

Is X.values() an array of the enum X?
Yes.

More info: Java 5.0 Language Features - Typesafe Enums


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Cate van Alphen:
I'm a bit confused about where the .values() comes from.


From the Java Language Specification...


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting a random element from an Enum