If i have heterogeneous collection for which I know exactly the types i’m going to place is there a way to enforce this.
For example take this scenario say i have a map that has a String key and value which can be on of three unrelated types. Now I know that I will only put ClassA and ClassB or java.lang.String
for example here is the code
public HetroCollection
{
public Map<String,Object> values;
}
public ClassA
{
}
public ClassB
{
}
public static void Main(String args[])
{
HetroCollection collection = new HetroCollection();
collection.values.add("first", new ClassA());
collections.values.add("second", new ClassB());
collections.values.add("third" , "someString");
//BAD want to stop random adds
collections.values.("fourth" , new SomeRandomClass());
}
The Options I have thought of are:
-
have the classes implement a common interface and use Generics on the Map (Problem with this is if this also involves library classes either JDK or third party then changing class is not an option
-
hide the Map and provide put Methods which are paratemized like
put(String key , ClassA value);
put(String key , ClassB value);
put(String key, String value);
get(String key); -
Rethink design and not use heterogeneous collection (not sure how I would represent this any other way)
Looking for the best practice answer for this.
I think that the “best practice” solutions are either your first and third options, provided that circumstances allow it.
Another option that you haven’t considered is something like this:
You could combine this with your second option so that there is a statically typed option, and possibly even label the
put(String, Object)method as deprecated to discourage its use.And finally, there is the option of just ignoring the problem, and relying on the application programmer to not put random stuff into the map. Depending on the circumstances, this might even be the best solution.