我有以下處理代碼EligibilityType:public enum EligibilityType { E (EligibilityTypeEnum.ELIGIBLE), I (EligibilityTypeEnum.INELIGIBLE); private final EligibilityTypeEnum eligibilityTypeEnum; private EligibilityType(EligibilityTypeEnum eligibilityTypeEnum) { this.eligibilityTypeEnum = eligibilityTypeEnum; } public EligibilityTypeEnum toEligibilityTypeEnum() { return eligibilityTypeEnum; }}我了解到,所有沒有價值“E”的東西都應該設置為EligibilityTypeEnum.INELIGIBLE.這就是我所說的:...List<Workout> workouts = workoutResults.getWorkout();for(int i = 0; i< workouts.size(); ++i) { ... stin.getWorkouts().get(i).setEligibilityType(EligibilityType.valueOf(workouts.get(i).getRecommendation()).toEligibilityTypeEnum()); ...}現在,如果workouts.get(i).getRecommendation()返回“C”,代碼就會爆炸。有沒有人看到任何其他方式來實現這一點除了try-catch?有沒有辦法在枚舉中設置默認值?
1 回答

莫回無
TA貢獻1865條經驗 獲得超7個贊
您可以在EligibilityType
地圖中擁有所有可能的值
public static final Map<String, EligibilityType> ALL_MAP = Arrays.stream(values()) .collect(Collectors.toMap(Enum::toString, Function.identity()));
那么你可以優(yōu)雅地處理默認情況
EligibilityType.ALL_MAP.getOrDefault(someString, EligibilityType.DEFAULT)
添加回答
舉報
0/150
提交
取消