Problem with generics syntax, or am I expecting too much?

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?
 
T

Thomas Hawtin

David said:
// 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.
// Return the map in the most general way possible.
Map<Integer, Iterable<Device>> getMap () {
return deviceMultimap;
}
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?

Client code could take the returned Map<Integer, Iterable<Device>> and
put a value of type TreeSet<Device> in it. That confuses the type of the
original deviceMultimap.

There are a couple of ways to fix the problem. Either declare
deviceMultimap as:

HashMap<Integer, Iterable<Device>> deviceMultimap;

Or getMap as:

Map<Integer, ? extends Iterable<Device>> getMap() {

Having said that, you probably don't want to return an uncopied version
of a mutable value.

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,227
Latest member
Daniella65

Latest Threads

Top