Question

I have the following code (java se 6):

import org.javatuples.Pair;

final SortedMap<Pair<AbstractEnum<?>, String>, AdapterObject> myMap = 
         new TreeMap<Pair<AbstractEnum<?>, String>();
myMap.put(Pair.with(SubTypeEnum.ITEM1, StringUtils.EMPTY), new AdapterObject());

AbstractEnum and SubTypeEnum are just:

public final class SubTypeEnum extends AbstractEnum<SubTypeEnum>
...
public abstract class AbstractEnum<T extends AbstractEnum<T>> implements Comparable<T>, Serializable

Now, the compiler says:

The method put(Pair<AbstractEnum<?>,String>, AdapterObject) in the type Map<Pair<AbstractEnum<?>,String>,AdapterObject> is not applicable for the arguments (Pair<SubTypeEnum,String>, new AdapterObject())

Any ideas how I can fix this?

Was it helpful?

Solution

Change the declaration to:

final SortedMap<Pair<? extends AbstractEnum<?>, String>, AdapterObject> myMap = 
            new TreeMap<Pair<? extends AbstractEnum<?>,String>, AdapterObject>();

OTHER TIPS

I believe that you'll find this

final SortedMap<Pair<AbstractEnum<?>, String>, AdapterObject> myMap = 
     new TreeMap<Pair<AbstractEnum<?>, String>();

should really be this

final SortedMap<Pair<AbstractEnum<SubTypeEnum>, String>, AdapterObject> myMap = 
     new TreeMap<Pair<AbstractEnum<SubTypeEnum>, String>();

Just like how String is a subtype of Object, but List<String> is not a subtype of List<Object>,

SubTypeEnum is a subtype of AbstractEnum<SubTypeEnum>, but Pair<SubTypeEnum,String> is not a subtype of Pair<AbstractEnum<SubTypeEnum>,String> or Pair<AbstractEnum<?>,String> or Pair<anything other than SubTypeEnum,String>

What you should do depends on what your intended use of this type is. If you want to only read the enum out of the pair (and never put it in), then Pair<? extends AbstractEnum<?>, String> will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top