Stephen D
Stephen D

Reputation: 3076

Subclass generics in hash maps?

 public class people {

}

class friend extends people {

}

class coworkers extends people {

}

class family extends people {

}

public void fillMaps(){
    ConcurrentMap<String, Collection<family>> familyNames = new ConcurrentHashMap<String, Collection<family>>();
    ConcurrentMap<String, Collection<coworkers>> coworkersNames = new ConcurrentHashMap<String, Collection<coworkers>>();
    ConcurrentMap<String, Collection<friend>> friendNames = new ConcurrentHashMap<String, Collection<friend>>();
    populateMap(family.class, familyNames);
    populateMap(coworkers.class, coworkersNames);
    populateMap(friend.class, friendNames);
}

private <T> void populateMap(Class<T> clazz, ConcurrentMap<String, Collection<people>> map) {
        if (clazz == family.class) {
            map.put("example", new ArrayList<family>());
        }
        if (clazz == coworkers.class) {
            map.put("example", new ArrayList<coworkers>());
        }
        if (clazz == friend.class) {
            map.put("example", new ArrayList<friend>());
        }

}

family, coworkers, and friend classes all extend from the superclass called people. Why doesn't the method below allow me to use the class as an argument to the parameters of the populateMap method. Also, why doesn't it allow me to pass a subclass collection as an argument here?

error:
The method populateMap(Class<T>, ConcurrentMap<String,Collection<people>>) is not applicable for the arguments (Class<family>, ConcurrentMap<String,Collection<family>>)

Upvotes: 0

Views: 1170

Answers (3)

herman
herman

Reputation: 12305

Use

private <T> void populateMap(Class<T> clazz, ConcurrentMap<String, Collection<? extends people>> map) {
...
}

Collection<family> should be valid for Collection<? extends people> as family extends people. But it is probably not what you want, Rahul's answer is what you probably want.

Upvotes: 0

rahul maindargi
rahul maindargi

Reputation: 5655

ArrayList<family> isn't considered as a subtype of Collection<people> ArrayList<family> subtype of Collection<family> ArrayList<people> subtype of Collection<people>

you want to have this

private <T extends people> void populateMap(ConcurrentMap<String, Collection<T>> map) {

                map.put("example", new ArrayList<T>());


    }

Upvotes: 3

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

Because, ArrayList<family> isn't considered as a subtype of Collection<people> and hence cannot be assigned. The concept of Polymorphism doesn't extend to Java generics the same way as they do to classes.

private <T> void populateMap(ConcurrentMap<String, Collection<T>> map) {
    map.put("example", new ArrayList<T>());
}

Upvotes: 3

Related Questions