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?
If you can switch, switch. It will always be as fast as if not faster than a hashmap. For integer values and enum values, it is transformed into an in memory lookup table, which doesn't have the cost of hashing. For a string, it creates the HashMap and uses that to switch.
ArrayList stores the elements only as values and maintains internally the indexing for every element. While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively.
There is no big difference between if-else and switch but Map is 2 times faster.
Disadvantages of HashMap A custom implementation of HashMap in Java can be found in this article. Potential of collision when 2 distinct keys generate the same hashCode() value worse the performance of the hashMap. Occasionally HashMaprequires resizing when the original size of HashMap buckets are full.
Initialize MAP
in a static block.
And since you will be creating many objects of Message.you should write code like this
public class Message {
private static HashMap tagMap;
static {
tagMap = new HashMap();
tagMap.put( 1, "tag1Name");
tagMap.put( 2, "tag2Name");
tagMap.put( 3, "tag3Name");
}
public Message() {
}
public String getTagName( int tagNumber) {
return tagMap.get( tagNumber);
}
}
Map can be used as command pattern in which key represents condition and value represents command to be executed the only drawback is object gets created before used so if you have large number of such conditions then you can opt for map else switch
is always elegant approach if your conditions are few.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With