Reputation: 46784
Is there a way to define a type for a Collection?
If I have the following:
private Map<String, A> myMap;
then is there a way to define Map<String, A>
as a new type MapOfTypeA, for example, so that I can define myMap as
private MapOfTypeA myMap;
as an extension of this, is there a way to have the following:
myMap = new MapOfTypeA();
actually be
myMap = new HashMap<String, A>();
I'm not sure of what to call what I am asking, but I think I have explained it. In C or C++ it would be a typedef, I think.
Upvotes: 2
Views: 793
Reputation: 1229
is that what you mean?
public class MapOfTypeA extends HashMap<String, A>{}
Then you could use your MapOfTypeA instances wherever you would need a HasMap.
...but I cannot really see where this would be useful(?)
Upvotes: 1
Reputation: 5560
I can think of at least two options
1) keep the value object generic, keys are always one type
public class StringKeyedMap<V> extends ConcurrentHashMap<String,V> {
public static void main(String[] args) {
StringKeyedMap<Integer> stringToIntegerMap = new StringKeyedMap<Integer>();
stringToIntegerMap.put("some-key", Integer.valueOf(7));
}
}
2) key and value of the map are always a single type
public class MyMap extends ConcurrentHashMap<String,Integer> {
public static void main(String[] args) {
MyMap myMap = new MyMap();
myMap.put("some-key", Integer.valueOf(7));
}
}
Upvotes: 1
Reputation: 4637
In Java Terms, it is call Generics: http://en.wikipedia.org/wiki/Generics_in_Java
And the way you defined it is perfectly correct.
but you probably need to revert how you define your hashmap.
If you want the hashmap to have both A and MapOfTypeA, and MapOfTypeA is a subclass of A
class MapOfTypeA extends A
, then your hashmap should defined this way.
HashMap<String, MapOfTypeA> myMap;
Upvotes: 0
Reputation: 28752
There are no typedefs
or aliases
in Java. The closest you can get is to create a new type, which is almost the same thing but not quite:
class MapOfA extends <String, A> {}
MapOfA aMap = new MapOfA();
The only place I have found this useful is for (sort of) partial specialization:
class MapFromString<X> extends Map<String, X> {}
Upvotes: 1
Reputation: 81429
Something like this?
class MapOfTypeA extends HashMap<String, A> { }
Which makes the following declaration perfectly valid:
private MapOfTypeA myMap;
That kind of class declaration is all you need to achieve the abbreviated syntax you're looking for. Of course the comments on why you're doing this will be an order of magnitude longer than the definition itself. ;-)
Upvotes: 1
Reputation: 328598
You could define MapOfTypeA as
class MapOfTypeA extends HashMap<String, A> {
}
But not sure what the purpose is. If your concern is verbosity, then Java 7 has introduced the diamond operator that you can use to declare your map like this:
Map<String, A> myMap = new HashMap<> ();
instead of
Map<String, A> myMap = new HashMap<String, A> ();
Upvotes: 3