使用泛型时在变量赋值中出错

时间:2013-11-11 11:02:30

标签: java generics

我已经制作了两个列表,如

List<LearnerEnrollment> learnerEnrollmentList = new ArrayList<LearnerEnrollment>();
List<LearnerCourseEnrollError> enrollErrorList = new ArrayList<LearnerCourseEnrollError>();

然后我制作了两张地图

Map<String, List<LearnerCourseEnrollError>> courseErrorMap = new HashMap<String, List<LearnerCourseEnrollError>>();
Map<String, List<LearnerEnrollment>> courseSuccessMap = new HashMap<String, List<LearnerEnrollment>>();

然后我制作了另一张地图来保存上面的两张地图,如

Map<String, Map<String, List<Object>>> courseMap = new HashMap<String, Map<String, List<Object>>>();

然后我使用以下代码在列表中添加项目;

for (com.softech.vu360.lms.model.Course course : courseList) {

    Object result = getEnrollmentForCourse(customer, learner, course);

    if (result instanceof LearnerEnrollment) {
        LearnerEnrollment newEnrollment = (LearnerEnrollment)result;
        learnerEnrollmentList.add(newEnrollment);
    } else if (result instanceof String) { 
        String errorMessage = (String)result;
        LearnerCourseEnrollError enrollError = new LearnerCourseEnrollError(errorMessage, course);
        enrollErrorList.add(enrollError);       
    }       
}

现在我将值放在地图

courseSuccessMap.put(learner.getVu360User().getUsername(), learnerEnrollmentList);
courseErrorMap.put(learner.getVu360User().getUsername(), enrollErrorList);
courseMap.put("successfulCoursesMap", courseSuccessMap);
courseMap.put("unSuccessfulCoursesMap", courseErrorMap);

return courseMap;

但我在这两行得到错误

courseMap.put("successfulCoursesMap", courseSuccessMap);
courseMap.put("unSuccessfulCoursesMap", courseErrorMap);

The method put(String, Map<String,List<Object>>) in the type
Map<String,Map<String,List<Object>>> is not applicable for the arguments 
(String, Map<String,List<LearnerEnrollment>>)

The method put(String, Map<String,List<Object>>) in the type
Map<String,Map<String,List<Object>>> is not applicable for the arguments 
(String, Map<String,List<LearnerCourseEnrollError>>)

为什么?

我在地图中的列表类型为List<Object>List<LearnerEnrollment>List <Object>,因为LearnerEnrollment extends Object。为什么我会收到这些错误?

如果我像这样声明我的地图

Map<String, Map<String, ?>> courseMap = new HashMap<String, Map<String, ?>>();

然后没有错误。为什么我在第一种情况下会收到错误?

由于

2 个答案:

答案 0 :(得分:6)

你说:

  

List<LearnerEnrollment>List<Object>

这是错误的。如果是真的,你可以这样做:

List<<LearnerEnrollment> list = new ArrayList<>();
List<Object> objectList = list;
objectList.add("Now what?");

你的类型安全的LearnerEnrollment列表会突然包含一个字符串。

答案 1 :(得分:1)

这是因为java中的List不是协变的。 List<LearnerEnrollment>不是List<Object>的子类。

有关详细信息,请参阅Java covariance