I am new to Java and I tried a couple of ways to initialize my HashMap through a method, but every time after method executed, my Map is still empty, I can debug and see during my LoadData
method execution, my maps are assigned with value from sub-method, however, when jumping out of the LoadData
, my outer parameter becomes empty Map again
// file1.java
public Map<String, Student> getStudentWithIdMap() { ... }
public Map<String, Teacher> getTeacherWithIdMap() { ... }
public static void LoadData(Map<String, Student> studentMap, Map<String, Teacher> teacherMap, ...other Map)
{
studentMap = getStudentWithIdMap();
//I tried with studentMap.putAll(getStudentWithIdMap());
// doing this triggers an exception like "UnsupportedOperationException"
// I also tried studentMap = new HashMap<>(getStudentWithIdMap());
teacherMap = getTeacherWithIdMap();
}
// file2.java
public void PrepareData() {
Map<String, Student> studentMap = Collections.emptyMap();
Map<String, Teacher> teacherMap = Collections.emptyMap();
file1.LoadData(studentMap, teacherMap, ...);
}
What would be the reason and the best way to deal with the above scenario?
I get to know Java treats method as value type always, so if passing a class object and modify its value, it would be modified after method finishes execution, why a Map behaves differently?