如果查找键是一个String,则为EnumMap或HashMap [英] EnumMap or HashMap if lookup key is a String
问题描述
我试图权衡使用 EnumMap
而不是 HashMap
的优缺点。因为,我总是使用 String
查找,似乎一个 HashMap
与 String
键将是正确的选择。然而, EnumMap
似乎更好的设计,因为它传达我的意图来限制键到一个特定的枚举。
这是一个相信的例子,显示了如何使用 Map
:
枚举AnimalType {CAT,DOG}
interface Animal {}
class Cat implements Animal {}
class Dog implements Animal {}
public class AnimalFactory {
private static final Map< AnimalType,Animal> enumMap
= new EnumMap< AnimalType,Animal>(AnimalType.class);
//对
private static final Map< String,Animal> stringMap
= new HashMap< String,Animal>();
static {
enumMap.put(AnimalType.CAT,new Cat());
enumMap.put(AnimalType.DOG,new Dog());
stringMap.put(CAT,new Cat());
stringMap.put(DOG,new Dog());
}
public static Animal(String type){
Animal result = enumMap.get(AnimalType.valueOf(type));
Animal result2 = stringMap.get(type);
return result;
}
}
假设 AnimalType
枚举和映射只能由 AnimalFactory
使用来创建动物,而不在其他地方。
如果所有有效的键都可以使用,那么 Map
枚举,我会使用它,因为它确保你总是使用一个有效的值。
它也可以避免混乱,因为String可以用于许多事情,很容易将Animal字符串转换为用于其他字符串的字符串。由于枚举类型通常不能与其他类型互换(除非使用通用接口),因此编码错误的可能性较小。
I'm trying to weigh the pros and cons of using an EnumMap
over a HashMap
. Since, I will always be looking up using a String
, it seems that a HashMap
with a String
key would be the right choice. However, an EnumMap
seems like better design because it conveys my intent to restrict keys to a specific enumeration. Thoughts?
Here is a make-believe example, showing how I will be using the Map
:
enum AnimalType { CAT, DOG }
interface Animal {}
class Cat implements Animal {}
class Dog implements Animal {}
public class AnimalFactory {
private static final Map<AnimalType, Animal> enumMap
= new EnumMap<AnimalType, Animal>(AnimalType.class);
// versus
private static final Map<String, Animal> stringMap
= new HashMap<String, Animal>();
static {
enumMap.put(AnimalType.CAT, new Cat());
enumMap.put(AnimalType.DOG, new Dog());
stringMap.put("CAT", new Cat());
stringMap.put("DOG", new Dog());
}
public static Animal create(String type) {
Animal result = enumMap.get(AnimalType.valueOf(type));
Animal result2 = stringMap.get(type);
return result;
}
}
Assume that the AnimalType
enum and map will ONLY be used by the AnimalFactory
to create animals and nowhere else.
Which Map
should I use?
If all valid keys can be enumerated, I would use that as it ensures you are always working with a valid value.
It can also avoid confusion as String can be used for lots of things and is easy to turn an "Animal" string into a string used for something else. As enum types are not interchangable with other types in general (unless you use a common interface), there is less chance of error in coding.
这篇关于如果查找键是一个String,则为EnumMap或HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!