Created
December 19, 2016 19:56
-
-
Save infomaven/37477e12e6684e8b9b3697ddfb010b73 to your computer and use it in GitHub Desktop.
Enum optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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