D
David Cogen
I have a map from integer to a set of "Device" objects. Internally it is a HashMap
from Integer to HashSet<Device>:
// A map from integer to a set of Device objects.
HashMap<Integer, HashSet<Device>> deviceMultimap;
I want a function to return this map, but in a generic way because I want the freedom
to change the implementation.
Since HashMap<K,V> implements Map<K,V>, I figure I could return the Map interface
instead of HashMap<>.
And since HashSet<E> implements Iterable<E>, I figure I could return the Iterable
interface instead of HashSet<>.
But when I put these together, I get the following function, which is not accepted by Java:
// Return the map in the most general way possible.
Map<Integer, Iterable<Device>> getMap () {
return deviceMultimap;
}
It claims there is a mismatch between the type of deviceMultimap and the type of the
result I am trying to return.
Am I expecting too much from Java generics syntax? It seems like a reasonable thing
to expect to do. Or have I got the syntax slightly wrong?
from Integer to HashSet<Device>:
// A map from integer to a set of Device objects.
HashMap<Integer, HashSet<Device>> deviceMultimap;
I want a function to return this map, but in a generic way because I want the freedom
to change the implementation.
Since HashMap<K,V> implements Map<K,V>, I figure I could return the Map interface
instead of HashMap<>.
And since HashSet<E> implements Iterable<E>, I figure I could return the Iterable
interface instead of HashSet<>.
But when I put these together, I get the following function, which is not accepted by Java:
// Return the map in the most general way possible.
Map<Integer, Iterable<Device>> getMap () {
return deviceMultimap;
}
It claims there is a mismatch between the type of deviceMultimap and the type of the
result I am trying to return.
Am I expecting too much from Java generics syntax? It seems like a reasonable thing
to expect to do. Or have I got the syntax slightly wrong?