HashMap访问相同的ArrayList



我正在尝试以下操作,用student的新值更新HashMap,请检查我遗漏了什么。

ArrayList<Student> tempStudentList = XMLParser.studentHashMap.get(currentSectionName);
if(studentList==null)
{
    Log.v(CURRENT_SCREEN,"created another student list for section name:"+currentSectionName);
    tempStudentList = new ArrayList<Student>();
} 
Log.v(CURRENT_SCREEN,"Added student to the list");
tempStudentList.add(currentStudent);
XMLParser.studentHashMap.put(currentSectionName, tempStudentList);

我想您想在null检查时编写tempStudentList而不是studentList

您正在检查错误的变量是否为null。此外,Java集合是可变的,studentHashMap中的数组是直接操作的,因此您不需要在映射上的每个查询之后执行另一个put:

ArrayList<Student> tempStudentList = XMLParser.studentHashMap.get(currentSectionName);
if(tempStudentList == null)
{
    Log.v(CURRENT_SCREEN, "created another student list for section name:"+currentSectionName);
    tempStudentList = new ArrayList<Student>();
    XMLParser.studentHashMap.put(tempStudentList);
} 
tempStudentList.add(currentStudent);
Log.v(CURRENT_SCREEN,"Added student to the list");

最新更新