0

How can I define a map like this in Java?

Map<Class<T extends myObject>, MyObjectConverter<T>>

The problem is the T in both arguments. T should be different for each map entry. But I want the map to be restricted to key-value-pairs that "share a common T"

The following definition works, but I think there must be a better way - without CompilerWarnings:

Map<Class<? extends myObject>, MyObjectConverter>
8
  • What is T? Where is it declared? Commented Jun 26, 2015 at 16:32
  • Thats the point: T should be different for each map entry. But I want the map to be restricted to key-value-pairs that "share a common T" Commented Jun 26, 2015 at 16:34
  • Wait a second. You want T to be different for each entry? Commented Jun 26, 2015 at 16:36
  • This is impossible. Sorry. Commented Jun 26, 2015 at 16:37
  • "T should be different for each map entry. But I want the map to be restricted to key-value-pairs that "share a common T" - What you've described and what you've hacked with code that results in warnings isn't quite in sync. You said you want T to be different for each key-value, but you want those T's to share a common superclass (eg: E). Is the superclass of T an actual concrete class, or is that supposed to be variable as well? Commented Jun 26, 2015 at 16:41

1 Answer 1

1

Let's say you have a class that implements a Map.

public class Cache<T> implements Map<... something ...> {
}

the main issue is that you need to clarify in your class declaration of T, not in the constraint of the Map interface.

public class Cache<T extends MyObject> implements Map<T, MyObjectConverter> {
  ...
}

Likewise (for methods and such) you need to clarify the generic "type" of T prior to using it in constraining parameters.

public <T extends MyObject> Collection<T> doFunc(T input, MyObjectConverter converter) {
  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Technically, this wouldn't satisfy the constraints; if the OP desire to have a different T for each map entry, then this would still bind T to have an upper bound of some concrete class.
@Makoto - this would satisfy what he wants because he's asking how to set it up so that the type T is a sub-class of some concrete type (MyObject)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.