I have a very simple Enum as follows:
public enum Colour {
RED, BLUE, GREEN;
}
Here I've put three colours, but it may have a undefined size.
This Enum will be used in a class which can have an undefined number of instances (hundreds, thousands or even millions).
In this class I have a method that must return a random Colour.
I have two options for this.
private Colour[] colours;
public Datastructure() {
colours = Colour.values();
}
public Colour getRandomColour() {
return colours[rand.nextInt() % colours.length];
}
Or I can keep calling Colour.values() instead of creating the colours list.
public Colour getRandromColour() {
return Colour.values()[rand.nexInt() % Colour.values().length]
In the first option, an extra array is created. Keep in mind that this class may have many instances, so it could be considered a waste of memory, and may have a impact on running time as well (instantiating the array). Especially when there are a lot of class instances.
In the second option, Colour.values() is called a few times (in this simple example it is only a few times but in my project it's bit more complex and has more calls) so this can be considered a waste of CPU usage.
I would prefer using the second option, but I'm curious about the complexity of the Colour.values() method, which I fear may be linear O(n). n being the number of Colours in the enum. This would be horrible when there are a lot of colours.
Or would it just be a weigh off and choose the best of two evils?
tl;dr What is the complexity of Enum.values()?