publicenumMutableExample { A, B;privateint count =0;publicvoidincrement() { count++; }publicvoidprint() {System.out.println("The count of "+name()+" is "+ count); }}
classMain {publicstaticvoidmain(String[] args) {MutableExample a =MutableExample.A;a.increment();a.print();MutableExample b =MutableExample.B;b.print(); }}
Enum constants are technically mutable, so a setter could be added to change the internal structure of an enum constant. However, this is considered very bad practice and should be avoided. Best practice is to make
Enum fields immutable, with final :
public enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
private final int value;
Coin(int value){
this.value = value;
}
...
}
importjava.util.*;enumdays { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}publicclassMain {publicstaticvoidmain(String[] args) {Set<days> set =EnumSet.of(days.TUESDAY,days.WEDNESDAY);// Traversing elementsIterator<days> iter =set.iterator();while (iter.hasNext())System.out.println(iter.next()); }}
Enum starting with number
Java does not allow the name of enum to start with number like 100A, 25K. In that case, we can append the code with _ (underscore) or any allowed pattern and make check of it.