19

I want to assign ui-Classes to a model-class each. By this I want to find the class where to store the date from the user interface. Please don't refer to the design but to my question on a HashMap's usage ;-)

I am aware of the class HashMap but only used it to assign objects to other objects.

How can I manage to link always two CLASSES with each other?

public static final HashMap<class,class> componentMap=new HashMap<class, class>();
componentMap.put(ToolPanel.class, ToolComponent.class);

The code above does not work...

3 Answers 3

34

You want a Map<Class<?>, Class<?>>.

Class here refers to java.lang.Class, which is a generified type. Unless you have more specific bounds, the unbounded wildcard <?> can be used (see Effective Java 2nd Edition, Item 23: Don't use raw types in new code)

Note that the interface Map is used here instead of a specific implementation HashMap (see Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces).

Note that Map<Class<?>, Class<?>> still maps objects, but the type of those objects are now Class<?>. They are still objects nonetheless.

See also

Related questions


Imposing restrictions with bounded wilcards

Here's an example of imposing bounded wildcards to have a Map whose keys must be Class<? extends Number>, and values can be any Class<?>.

    Map<Class<? extends Number>, Class<?>> map
        = new HashMap<Class<? extends Number>, Class<?>>();

    map.put(Integer.class, String.class);        // OK!
    map.put(Long.class, StringBuilder.class);    // OK!

    map.put(String.class, Boolean.class);        // NOT OK!
    // Compilation error:
    //     The method put(Class<? extends Number>, Class<?>)
    //     in the type Map<Class<? extends Number>,Class<?>>
    //     is not applicable for the arguments (Class<String>, Class<Boolean>)

As you can see, the generic compile-time typesafety mechanism will prevent String.class from being used as a key, since String does not extends Number.

See also

Sign up to request clarification or add additional context in comments.

2 Comments

I only have the constraints that the key-class extends ClassR and the value-class extends classB. Can this be specified in the generics?
@kerrl - Map<Class<? extends ClassR>, Class<? extends ClassB>>
3

It should have been:

HashMap<Class,Class>

(capital C)

or better:

HashMap<Class<?>,Class<?>>

1 Comment

Thanks for your response. To what extend does Class<?> differ to Class, what's the generic's effect?
2

The declaration should be:

public static final HashMap<Class<?>, Class<?>> componentMap = new HashMap<Class<?>, Class<?>>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.