So I have three enums and I want to make an ArrayList out of them. Here's my code:
enum Outlook {
SUNNY, RAINY, CLOUDY
}
enum Temperature {
HOT, COLD, MILD
}
enum Humidity {
HIGH, NORMAL, LOW
}
And I want my ArrayList to look something like:
{Outlook, Temperature, Humidity}
Here's what I've tried:
ArrayList<Enum> attributes = new ArrayList<Enum>();
attributes.add(Temperature);
But already Eclipse tells me "Temperature cannot be resolved to a variable". Any idea how to achieve what I'm aiming for here?
I'm surmising that you want the names of the enums themselves, and not their values. As such, try the following code:
public static void main (String[] args) throws java.lang.Exception
{
List<Class<? extends Enum>> myEnums = new ArrayList<>();
myEnums.add(Outlook.class);
myEnums.add(Temperature.class);
myEnums.add(Humidity.class);
System.out.println(myEnums);
}
enum Outlook {
SUNNY, RAINY, CLOUDY
}
enum Temperature {
HOT, COLD, MILD
}
enum Humidity {
HIGH, NORMAL, LOW
}
You can see the demo here which will output:
[class Ideone$Outlook, class Ideone$Temperature, class Ideone$Humidity]
If you strictly need something like:
[Outlook, Temperature, Humidity]
and just can't like the extra class Ideone$...
info then we can add some extra sophistication.
I want to loop through all of the classes (Outlook, Temp, Humidity) and, for each of them, calculate information gain. This is a function that makes use of each possible value of a given attribute (Outlook, Temp, Humidity).
One possibility would be to define a common interface implemented by all the attributes. This would allow your information-gain function to use the same interface regardless of attribute. And no reflection is required. For example:
interface IAttribute {
Enum<?>[] getValues();
String getName();
}
This interface applies to attribute classes as a whole, and not a particular attribute value. Here's one way to do that.
private static final class OutlookAttribute implements IAttribute {
enum Outlook { SUNNY, RAINY, CLOUDY }
@Override
public Outlook[] getValues() { return Outlook.values(); }
@Override
public String getName() { return "Outlook"; }
}
// And similarly for Temperature and Humidity
Now you can create a list of attributes to pass to your function.
List<IAttribute> attributes = new ArrayList<>();
attributes.add( new OutlookAttribute() );
attributes.add( new TemperatureAttribute() );
attributes.add( new HumidityAttribute() );
And your function definition can iterate through attributes.
for ( IAttribute attribute : attributes ) {
Object[] values = attribute.getValues();
...
for ( Object value : values ) {
...
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With