File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting a random element from an Enum

 
Cate van Alphen
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 781
Java Netbeans IDE Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given an enum say
enum X {a,b,c,d,e,f}
then

 
Cate van Alphen
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Cate van Alphen:
I'm a bit confused about where the .values() comes from.


From the Java Language Specification...
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic