This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting a random element from an Enum

 
Cate van Alphen
Greenhorn
Posts: 16
  • 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
  • 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
  • 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
Posts: 15208
36
Android IntelliJ IDE Java Scala Spring
  • 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
  • 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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic