Last active
January 18, 2020 14:53
-
-
Save mascot27/e8ba7e8322df9e2f5b933eb44b45a653 to your computer and use it in GitHub Desktop.
enum usage
This file contains hidden or 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
| package com.company; | |
| import java.util.Arrays; | |
| import java.util.Collections; | |
| import java.util.List; | |
| import java.util.Random; | |
| enum Letter { | |
| RougeVif, | |
| Mauve, | |
| Orange, | |
| Rose; | |
| private static final List<Letter> VALUES = | |
| Collections.unmodifiableList(Arrays.asList(values())); | |
| private static final int SIZE = VALUES.size(); | |
| private static final Random RANDOM = new Random(); | |
| public static Letter randomLetter() { | |
| return VALUES.get(RANDOM.nextInt(SIZE)); | |
| } | |
| /* | |
| usage example | |
| */ | |
| public static void display(Letter s) { | |
| System.out.println(s.name()); | |
| } | |
| public static void enumIterate() { | |
| for (Letter s : Letter.values()) { | |
| System.out.println(s.name()); | |
| } | |
| } | |
| public static void enumSwitchExample(Letter s) { | |
| switch(s) { | |
| case Mauve: | |
| System.out.println("It's pretty cold"); | |
| break; | |
| } | |
| } | |
| /* | |
| mutable: counter for each is private | |
| */ | |
| private int count = 0; | |
| public void print() { | |
| System.out.println("The count of " + name() + " is " + count); | |
| } | |
| // possible de faire un setter de count public pour changer la valeur | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment