有一个消息类可以根据标签号返回标签名
由于该类被实例化多次,我有点不愿意为每个实例创建一个HashMap:
public class Message {
private HashMap<Integer,String> tagMap;
public Message() {
this.tagMap = new HashMap<Integer,String>();
this.tagMap.put( 1, "tag1Name");
this.tagMap.put( 2, "tag2Name");
this.tagMap.put( 3, "tag3Name");
}
public String getTagName( int tagNumber) {
return this.tagMap.get( tagNumber);
}
}
支持硬编码的理由:
public class Message {
public Message() {
}
public String getTagName( int tagNumber) {
switch( tagNumber) {
case 1: return "tag1Name";
case 2: return "tag2Name";
case 3: return "tag3Name";
default return null;
}
}
}
当你把所有东西都考虑进去(内存,性能,垃圾回收,...)
有没有理由坚持使用HashMap?