Java hardcoded switch vs hashmap

Viewed 9142

Some Message class is able to return a tag name based on tag number

Since this class is instanciated many times, I am a bit reluctant to create a HashMap for each instance:

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);
  }
}

In favor of hardcoding:

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;
    }
  }
}

When you put everything in the mix ( Memory, Performance, GC, ...)

Is there any reason to stick to HashMap?

5 Answers
Related