Skip to content

Instantly share code, notes, and snippets.

@JoeyChor
Created September 21, 2016 23:08
Show Gist options
  • Save JoeyChor/dabb77308ef3733e30a2a854b710f6a4 to your computer and use it in GitHub Desktop.
Save JoeyChor/dabb77308ef3733e30a2a854b710f6a4 to your computer and use it in GitHub Desktop.
Misc. utilities for java
public class TestToggleEnum {
enum TestEnum {
A,
B,
C
}
@Test
public void incrementEnum() {
TestEnum test = TestEnum.A;
test = Utils.toggleEnum(true, test);
assertEquals(test, TestEnum.B);
}
@Test
public void decrementEnum() {
TestEnum test = TestEnum.C;
test = Utils.toggleEnum(false, test);
assertEquals(test, TestEnum.B);
}
@Test
public void incrementEnumOverflow() {
TestEnum test = TestEnum.C;
test = Utils.toggleEnum(true, test);
assertEquals(test, TestEnum.A);
}
@Test
public void decrementEnumOverflow() {
TestEnum test = TestEnum.A;
test = Utils.toggleEnum(false, test);
assertEquals(test, TestEnum.C);
}
}
public class Utils {
/**
* Toggle the enum either forward or reverse
* @param forward If the enum should go down the enum (true) or up the enum (false)
* @param enums The enum value
* @return The new, same-type enum
*
* @author joeychor
*/
@SuppressWarnings("unchecked")
public static <T extends Enum<?>> T toggleEnum(boolean forward, Enum<? extends T> enums) {
int offset = forward ? 1 : -1;
int index = enums.ordinal();
int length = enums.getClass().getEnumConstants().length;
if ((index + offset) >= length) {
return (T) enums.getClass().getEnumConstants()[0];
} else if ((index + offset) < 0) {
return (T) enums.getClass().getEnumConstants()[length - 1];
} else {
return (T) enums.getClass().getEnumConstants()[index + offset];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment