Link to home
Start Free TrialLog in
Avatar of deleyd
deleydFlag for United States of America

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:
public enum Units {
	
	CELSIUS(MeasurementType.TEMPERATURE),
	FAHRENHEIT(MeasurementType.TEMPERATURE);

	
	private final MeasurementType measurementType;

	//CONSTRUCTORS
	private Units(MeasurementType measurementType) {
		this.measurementType = measurementType;
	}
}

Open in new window

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;
	}
}

Open in new window

public class Measurement {

	private final double value;
	private final Units units;
	
	public Measurement(double value, Units units) {
		this.value = value;
		this.units = units;
	}
}

Open in new window

public class Test {

    public static void main(String[] args) {
	    Measurement measurement = new Measurement(13.1, Units.CELSIUS);
    }
}

Open in new window

Output:
MeasurementType:CONSTRUCTOR: ul=[null, null]

(was hoping for ul=[CELSIUS, FAHRENHEIT])
ASKER CERTIFIED SOLUTION
Avatar of dpearson
dpearson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of deleyd

ASKER

Yup that's pretty much what I figured after taking a break and eating some dinner.

I was trying to make it easy by having the info right there, and it ended up making it hard.
Avatar of dpearson
dpearson

Dinner solves many a hard problem :)

Doug