0

I want a method argument to define the class a HashMap will accept. Something along the lines of:

private HashMap hashMap = new HashMap();

public boolean createMap(Object obj) {
    return hashMap = new HashMap<String, obj.getClass()>() != null;
}
7
  • 1
    How about public boolean <T> createMap() { return hashMap = new HashMap<String, T>() != null; }? Did you try your example? What is the error you receive? Commented Dec 18, 2013 at 19:59
  • 1
    this method will always return true Commented Dec 18, 2013 at 20:03
  • @crush: It expects '>' instead of () after .getClass Commented Dec 18, 2013 at 20:05
  • @hoaz It will? Noted. Commented Dec 18, 2013 at 20:06
  • @crush: Your example still allows any object type with .put() Commented Dec 18, 2013 at 20:32

2 Answers 2

5

You can't do what you're trying to do: you can't "define the class a HashMap will accept" because at runtime a HashMap will accept all classes.

What you could do, on the other hand, is:

private Map<String, ?> map;

public <V> void createMap(Class<V> clazz) {
   map = Collections.checkedMap(new HashMap<String, V>(),
      String.class, clazz);
}

...which will actually enforce the restrictions you're trying to create, with reflection. In this case, your hashMap member should have type Map<String, Object>, though it will enforce

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

3 Comments

It cannot find 'V' in Class<V>
Did you mean public <V>? What is T used for in that example?
Whoops, yes, I meant <V>.
0

define a typed function that accepts the type you desire as value for the map

public <T> Map<String, T> checkedStringKeyMap(Class<T> type) {
    return Collections.checkedMap(new HashMap<String, T>(), String.class, type);
}

then create your map as follows

Map<String, Person> persons = checkedStringKeyMap(Person.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.