Reputation: 65
I am creating a factory method for a Hashmap in a public class.
public class MyList {
Hashmap list = newMap(); //is this function called properly here?
public static final Hashmap newMap() {
return Hashmap(String, boolean);
}
}
In the simplest way, how do I set up the factory method if it is to hold a string and boolean for the key/value pair?
I'm stuck on the syntax.
I just want to return a new Hashmap object and use newMap() as a factory method
Upvotes: 1
Views: 1104
Reputation: 193
To get a generic factory method with T and U as Class type you can go ahead with
public static <T,U> HashMap<T,U> factoryHashMap(T t , U u ){
HashMap<T,U> tuHashMap = new HashMap<T,U>();
// do stuff
return tuHashMap;
}
Here T t, Uu
are optional params . You can have empty params too .
If you observe before the return type HashMap<T,U>
in function, we have put <T,U>
to denote that this is a generic method
here T and U can be any valid class type . In your case it is String and Boolean
new HashMap<T,U>
is the instance that is created and updated to your factory method's requirements .
for eg . In the below example we are simply adding t
and u
to the map, if they are not null else returning an empty HashMap
public static <T, U> HashMap<T, U> factoryHashMap(T t, U u) {
HashMap<T, U> tuHashMap = new HashMap<T, U>();
if (t != null && u != null)
tuHashMap.put(t, u);
return tuHashMap;
}
driver method :
public static void main(String args[] ) throws Exception {
HashMap<String, Boolean> myMap = factoryHashMap("isItCool?",false);
}
Upvotes: 0
Reputation: 54168
HashMap
has generic types for key and value, so you need to specify these types as
public static HashMap<String, Boolean> newMap() {
// ...
}
And inside, you'll create the map as
return new HashMap<String, Boolean>();
return new HashMap<>();
using diamond operator (as type is already in the signature You could also pass the type as parameter
public static <K, V> HashMap<K, V> newMap(Class<K> classKey, Class<V> classValue) {
return new HashMap<>();
}
Use
public static void main(String[] args) {
Map<String, Boolean> map = newMap();
Map<Integer, Double> mapID = newMap(Integer.class, Double.class);
}
Upvotes: 1