Consider this HashMap extention (generates an instance of the V class when calling "get" if it's null)
public class HashMapSafe<K, V> extends HashMap<K, V> implements Map<K, V>{
private Class<V> dataType;
public HashMapSafe(Class<V> clazz){
dataType = clazz;
}
@SuppressWarnings("unchecked")
@Override
public V get(Object key) {
if(!containsKey(key)){
try {
put((K)key, dataType.newInstance());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return super.get(key);
}
}
The usage of it is something like this
Map<String,Section> sections = new HashMapSafe<String,Section>(Section.class);
sections.get(sectionName); //always returns a Section instance, existing or new
It seems to me redundant a little to supply "Section" twice, once as a generic type, and also supply it's class. I assume it's impossible, but is there to implement HashMapSafe, (keeping the same functionality) so it can be used like this?
Map<String,Section> sections = new HashMapSafe<String,Section>();
Or like this?:
Map<String,Section> sections = new HashMapSafe<String>(Section.class);
The only way to "stop" a constructor is to throw an exception.
Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created.
All Java classes have at least one constructor even if we don't explicitly define one. In this article, we'll cover the behavior of the default constructor which sometimes causes confusion among new Java developers.
The constructors can appear anywhere in the code for the class. However, by convention, most people put them before any other functions that aren't constructors.
You cannot improve the constructor usage due to type erasure as others have already pointed out, but you should be able to improve verbosity by using a static factory method instead of a constructor...
I am not in front of compiler and I can never get method type parameters right on first try, but it will go something like this...
public static <K,V> Map<K,V> create( Class<V> cl )
{
return new HashMapSafe<K,V>(cl);
}
...
Map<String,Section> sections = HashMapSafe.create(Section.class);
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