Skip to content

Instantly share code, notes, and snippets.

@infomaven
Created December 19, 2016 19:56
Show Gist options
  • Save infomaven/37477e12e6684e8b9b3697ddfb010b73 to your computer and use it in GitHub Desktop.
Save infomaven/37477e12e6684e8b9b3697ddfb010b73 to your computer and use it in GitHub Desktop.
Enum optimization
// create an alternative method for getting a list of defined enums to avoid system creating a clone of the String array
// this is the .values() method
public enum Car {
TESLA, VOLVO, TOYOTA;
}
// normally what would happen
public static Car[] values() {
return (Car[])$VALUES.clone();
}
// HOW TO MITIGATE THIS BEHAVIOR
public enum Car {
TESLA, VOLVO, TOYOTA;
private static final List<Car> VALUE_LIST= Stream.of(values()).collect( collectingAndThen(toList(), Collections::unmodifiableList));
// VALUE_LIST is unmodifiable; otherwise we cannot expose it directly via the valuesAsList() method
public static List<Car> valuesAsList() {
return VALUE_LIST;
}
}
// example usage
Car.valuesAsList().forEach( System.out::println);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment