Selecting a random value from an enum

S

Steven Davies

Hi,

Say I have the following declaration:

enum Days {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY;
}

Is there any way I can get a random value out of it without using a for
loop of random size?

Thanks,

Steven Davies
 
J

John C. Bollinger

Steven said:
Say I have the following declaration:

enum Days {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY;
}

Is there any way I can get a random value out of it without using a for
loop of random size?

From reading the typesafe enum docs, I would expect that something
similar to this would work:

public Days randomDay() {
Days[] days = Days.values();

return days[(int) (Math.random() * days.length)];
}

I have not tested it, however.


John Bollinger
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top