Say I have this enumerated type of Colours as follows:
public enum Colour
{
RED, GREEN, BLUE;
}
I want to randomize a colour out of those three, following the suggestion found over there: https://stackoverflow.com/a/8114214/2736228
But I don't want to make a call to values()
over and over again, so, I came up with something as follows:
public enum Colour
{
RED, GREEN, BLUE;
private static final Colour[] Values = values();
public static Colour random()
{
return Values[(int) (Math.random() * Values.length)];
}
}
Question is, will it work, always?
What confuses me here, is that when the initialization of this private static final
field occurs. It should be happening after the full list of enumeration is completed. I don't see it happening anytime soon, but still, I want to make sure.