Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Ensuring the Numeric Values of Enum Constants

DZone's Guide to

Ensuring the Numeric Values of Enum Constants

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Problem statement: you have an Enum and you want to ensure that the numeric values returned by ordinal are a certain way (perhaps this Enum is part of a communication protocol with an external system or perhaps it is written to a DB using an ORM).

One solution would be to write a unit test like the following:

@Test
public void testEnum() {
	Map<TestEnum, Integer> expectedValues = new EnumMap<TestEnum, Integer>(TestEnum.class);
	expectedValues.put(TestEnum.FOO, 0);
	expectedValues.put(TestEnum.BAR, 1);
	expectedValues.put(TestEnum.BAZ, 2);

	assertEquals(TestEnum.values().length, expectedValues.size());
	for (Map.Entry<TestEnum, Integer> entry: expectedValues.entrySet()) {
		assertEquals(entry.getKey().ordinal(), entry.getValue().intValue());
	}
}

Of course this presupposes that the unittests are run frequently to catch any possible errors. Alternatively we can implement our Enum as shown below, which will check the values during load time (and prevent the loading of the enum by the classloader – by virtue of throwing an exception during the initialization phase – if the values are incorrect):

public enum TestEnum {
	FOO(0), BAR(1), BAZ(2);

	private static class CounterHolder {
		static int COUNTER = 0;
	}

	TestEnum(int order) {
		if (order != CounterHolder.COUNTER) {
			throw new IllegalArgumentException("Expected "
					+ CounterHolder.COUNTER + " but was " + order);
		}
		CounterHolder.COUNTER++;
	}
}

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}