0

I have following class which contains map containing generics of list of objects. I need to put a method addElement() and kind of confused about type of object.

What should be type of argument on method addElement() ???

public class Tester{
   private final ConcurrentMap<Date, List<? extends BaseObject>> map = new ConcurrentHashMap<>();

 ...
 ...
 public void addElement(Date d, BaseObject o){
        ...
        ...
    List<? extends BaseObject> list = map.get(d);
    if (null == list) {
        list = new ArrayList<>();
    }
    //add element
    list.add(o);<-------------- Compile error
    map.put(d,list); 
 }


}

Solution Changing code to following will fix the issue, LINK

public class Tester{ private final ConcurrentMap> map = new ConcurrentHashMap<>();

 ...
 ...
 public void addElement(Date d, BaseObject o){
        ...
        ...
    List<? super BaseObject> list = map.get(d);
    if (null == list) {
        list = new ArrayList<>();
    }
    //add element
    list.add(o);<-------------- Compile error fixed
    map.put(d,list); 
 }


}
Community
  • 1
  • 1
gpa
  • 2,411
  • 6
  • 38
  • 68

0 Answers0