Forum Stats

  • 3,760,212 Users
  • 2,251,664 Discussions
  • 7,871,021 Comments

Discussions

Returning a HashMap<K, M> from a method of a class typed<M>

843793
843793 Member Posts: 41,732 Green Ribbon
edited May 14, 2010 4:16PM in Generics
So, this is what I have. I have a class parameterized for a bean type of a collection it receives, and in a method of the class, I need (would like) to return a HashMap typed as <K, M> as in:
public class MyClass<M> {
   private Collection<M> beanList;

   public HashMap<K, M> getMap(  /* what do I do here */ );
}
I tried to cheat from looking at the Collections.sort method, knowing it uses the List type in its return type as in:
public static <T extends Comparable<? super T>> void sort(List<T> list)
So, I am trying:
public HashMap<K, M> getMap(Class<K> keyType)
But, it is telling me I need to create class K.

So... how does the Collections.sort method get away with it and I can't????

I suppose I could write the method as:
public HashMap<Object, M> getMap()
but became somewhat challenged by my first guess.

Any ideas... or just go with the HashMap with the untyped key?

Comments

  • EJP
    EJP Member Posts: 32,920 Gold Crown
    You can do
    public <K> HashMap<K, M> getMap(  /* what do I do here */ );
    provided K is inferable from the arguments.

    Otherwise you have to parameterise the class on <K, M>.
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    Oh how very nice! Thank you. I, for some reason, cannot fully get my head around generics, though I do everything I can to utilize them to their fullest.

    I didn't want to type the class because on each call of getMap, I might need a different type key, and didn't want to create singletons for my purpose.

    Thanks again!

    Joe
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    edited May 14, 2010 4:16PM
    ejp wrote:
    provided K is inferable from the arguments.
    Or from the assignment context:
    Set<String> empty = Collections.emptySet();
    Otherwise you have to parameterise the class on <K, M>.
    You may also specifically provide K when you use the method if the context doesn't give the compiler enough information or if you want to override it.

    Example:
    Set<Object> singleton1 = Collections.singleton("Hello"); //error
    Set<Object> singleton2 = Collections.<Object>singleton("Hello"); //fine
    Edited by: endasil on 14-May-2010 4:13 PM
This discussion has been closed.