Jan Koester
Jan Koester

Reputation: 1218

Java Generics in Method Declaration

   private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>();

    public <T> void putFavorite(Class<T> type, T instance) {
        //code to put the T Object in the Map
    }

I saw this code in a talk from Joshua Bloch on UserGroupsAtGoogle
link: http://www.youtube.com/watch?v=V1vQf4qyMXg

I wonder what this <T> means in the method declaration of the putFavorite method.
I assume, this is not the return value, because this is already void.

Upvotes: 3

Views: 144

Answers (2)

hburde
hburde

Reputation: 1441

is a type parameter which is replaced by the argument like in the example above. Here is a related faq : http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ001

Upvotes: 0

driangle
driangle

Reputation: 11779

You're right, it's not the return value, the <T> is declaring a generic type named T which will then be used in the signature of this method. For a client calling the method, they have to make sure the arguments they pass in satisfy the signature, such that T is consistent across all arguments (and return value in some cases).

Some valid ways to call the method would be:

putFavorite(String.class, "Some string");
putFavorite(Integer.class, Integer.valueOf(1234));
putFavorite(SomeClass.class, new SomeClass());

etc..

See this page for a more detailed explanation.

Upvotes: 10

Related Questions