1

我制作了两个列表,例如

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, ?>>();

那么就没有错误了。为什么我在第一种情况下会出错?

谢谢

4

2 回答 2

6

你说:

List<LearnerEnrollment>List<Object>

这是错误的。如果它是真的,你将能够做到:

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

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

于 2013-11-11T11:06:32.107 回答
1

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

有关更多信息,请参阅Java 协方差

于 2013-11-11T11:07:30.730 回答