• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Getting a random element from an Enum

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 781
Netbeans IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Create symphonies in seed and soil. For this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic