deleyd
asked on
Java circular enum constructors (catch 22)
I have an enum for MeasurementTypes, that says a TEMPERATURE measurement uses units CELSIUS or FAHRENHEIT.
Then I have a Units class which defines CELSIUS and FAHRENHEIT as being TEMPERATURE measurements.
I create a measurement, get the measurement type, and discover in the constructor for MeasurementType the TEMPERATURE measurement type doesn't have the units CELSIUS and FAHRENHEIT filled in.
I suppose because TEMPERATURE needs CELSIUS and FAHRENHEIT to already exist and be initialized, while CELSIUS and FAHRENHEIT need TEMPERATURE to already exist and be initialized.
Well that's a fine mess of spaghetti I've gotten myself into now. Any suggestions how to get around this?
Below is some sample code:
MeasurementType:CONSTRUCTO R: ul=[null, null]
(was hoping for ul=[CELSIUS, FAHRENHEIT])
Then I have a Units class which defines CELSIUS and FAHRENHEIT as being TEMPERATURE measurements.
I create a measurement, get the measurement type, and discover in the constructor for MeasurementType the TEMPERATURE measurement type doesn't have the units CELSIUS and FAHRENHEIT filled in.
I suppose because TEMPERATURE needs CELSIUS and FAHRENHEIT to already exist and be initialized, while CELSIUS and FAHRENHEIT need TEMPERATURE to already exist and be initialized.
Well that's a fine mess of spaghetti I've gotten myself into now. Any suggestions how to get around this?
Below is some sample code:
public enum Units {
CELSIUS(MeasurementType.TEMPERATURE),
FAHRENHEIT(MeasurementType.TEMPERATURE);
private final MeasurementType measurementType;
//CONSTRUCTORS
private Units(MeasurementType measurementType) {
this.measurementType = measurementType;
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public enum MeasurementType {
TEMPERATURE( new ArrayList<Units>(Arrays.asList( Units.CELSIUS, Units.FAHRENHEIT )) );
private List<Units> unitsList;
//CONSTRUCTORS
private MeasurementType(List<Units> ul) {
System.out.println("MeasurementType:CONSTRUCTOR: ul=" + ul);
this.unitsList = ul;
}
}
public class Measurement {
private final double value;
private final Units units;
public Measurement(double value, Units units) {
this.value = value;
this.units = units;
}
}
public class Test {
public static void main(String[] args) {
Measurement measurement = new Measurement(13.1, Units.CELSIUS);
}
}
Output:MeasurementType:CONSTRUCTO
(was hoping for ul=[CELSIUS, FAHRENHEIT])
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Dinner solves many a hard problem :)
Doug
Doug
ASKER
I was trying to make it easy by having the info right there, and it ended up making it hard.