1 package org.unicode.cldr.util; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.Locale; 6 import java.util.Map; 7 8 public class EnumNames<T extends Enum<?>> { 9 private Map<String, T> namesToEnum = new HashMap<String, T>(); 10 private ArrayList<String> enumToPreferredName = new ArrayList<String>(); 11 add(T enumItem, String... alternateNames)12 public void add(T enumItem, String... alternateNames) { 13 final String name = enumItem.name(); 14 namesToEnum.put(name, enumItem); 15 namesToEnum.put(name.toLowerCase(Locale.ENGLISH), enumItem); 16 // add() is safe, because we are guaranteed that they are added in order. 17 if (alternateNames.length == 0) { 18 enumToPreferredName.add(name); 19 } else { 20 enumToPreferredName.add(alternateNames[0]); 21 for (String other : alternateNames) { 22 namesToEnum.put(other, enumItem); 23 namesToEnum.put(other.toLowerCase(Locale.ENGLISH), enumItem); 24 } 25 } 26 } 27 forString(String name)28 public T forString(String name) { 29 T result = namesToEnum.get(name); 30 if (result != null) { 31 return result; 32 } 33 result = namesToEnum.get(name.toLowerCase(Locale.ENGLISH)); 34 if (result != null) { 35 return result; 36 } 37 throw new IllegalArgumentException("No enum value for " + name + ", should be one of " + namesToEnum.keySet()); 38 } 39 toString(T item)40 public String toString(T item) { 41 return enumToPreferredName.get(item.ordinal()); 42 } 43 }