Lets say we have a class called CompHash with 30 different variables as follows:
public class CompHash{
private String abc1;
private int sdf2;
:
:
private float sgh30;
}
and a similar class:
public class CompHash{
private HashMap diffVariables;
}
In a situation where the number of variables that I will be needing varies from 1 to 30, which of the two would be better?
In general you should always prefer strongly typed
CompHash(the first one). Not only it is safer, but it will also be significantly faster.If you have a requirement to store arbitrary number of variables,
HashMapmight be a good choice. But remember you are sacrificing type-safety without much gain –HashMapwill probably still occupy more memory as opposed to a single object with lots ofnulls.The only valid usage of
HashMapis when you need to store arbitrary pairs (it is not clear whether variables/key names are constant in your case) of key -> value. But in this scenario I would recommend wrapping primitives with a class hierarchy having common ancestor and usingVisitorpattern to avoid dangarous down-casts and uglyinstanceof‘s.BTW what problem are you actually solving? The data structure you need seems a bit exotic…