public enum Planet { MERCURY(3.302e+23, 2.439e6), VENUS (4.869e+24, 6.052e6), URANUS (8.683e+25, 2.556e7); private final double mercury; private final double venus; Planet(double mercury, double venus) { this.mercury = mercury; this.venus = venus; } }
這種方式較爲常見。
for (Planet planet : Planet.values()) { double mercury = planet.mercury; }
還有一種“算數的思路”,用IDEA還會有提示,更容易理解。
package test; import DataStructures.List.DoublyLinkedList; public enum Operation { PLUS("+") { public double apply(double x, double y) {return x + y; } }, MINUS("-") { public double apply(double x, double y) {return x - y; } }; private final String symbol; Operation(String symbol) { this.symbol = symbol; } public abstract double apply(double x, double y); public static void main(String[] args) { double x = Double.parseDouble("1.2"); double y = Double.parseDouble("2.4"); for (Operation operation : Operation.values()) { System.out.println(operation.apply(x, y)); } } }
一個賞心悅目的例子,這裏主要用了EnumMap
package test; import java.util.*; import static java.util.stream.Collectors.groupingBy; public class Plant { enum LifeCycle {ONE, TWO, THREE} final String name; final LifeCycle lifeCycle; public Plant(String name, LifeCycle lifeCycle) { this.name = name; this.lifeCycle = lifeCycle; } @Override public String toString() { return "Plant{" + "name='" + name + '\'' + ", lifeCycle=" + lifeCycle + '}'; } public static void main(String[] args) { Map<Plant.LifeCycle, Set<Plant>> map = new EnumMap<LifeCycle, Set<Plant>>(Plant.LifeCycle.class); Plant p1 = new Plant("no1", LifeCycle.ONE); Plant p2 = new Plant("no2", LifeCycle.TWO); Plant p3 = new Plant("no3", LifeCycle.ONE); Plant p4 = new Plant("no4", LifeCycle.THREE); Plant[] garden = {p1, p2, p3, p4}; for (Plant.LifeCycle lifeCycle : Plant.LifeCycle.values()) { map.put(lifeCycle, new HashSet<>()); } for (Plant plant : garden) { map.get(plant.lifeCycle).add(plant); } System.out.println(map); System.out.println(Arrays.stream(garden) .collect(groupingBy(p -> p.lifeCycle)) ); } }
最後用一段極其簡單的lambda也解決了,真是不可小覷。