One object is used as a key (index) to another object (value). A HashMap however, store items in 'key/value' pairs, and you can access them by an index of another type (e.g. You are not allowed to change that map, so writes will fail. In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number (int type). That will cause another Problem, because you initialized these variables with Collection.emptyMap(). TeacherMap.putAll( getTeacherWithIdMap() ) StudentMap.putAll( getStudentWithIdMap() ) To actually change that Map you need to insert the values into it.Į.g with: public static void LoadData(Map studentMap, Map teacherMap. The variable studentMap will point to the Map return by getStudentwithIdMap() that doesn't affect the Map referenced in variable studentMap in the PrepareData method. If you do something like studentMap = getStudentWithIdMap() 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? What would be the reason and the best way to deal with the above scenario? I also tried studentMap = new HashMap(getStudentWithIdMap()) įile1.LoadData(studentMap, teacherMap. doing this triggers an exception like "UnsupportedOperationException" I tried with studentMap.putAll(getStudentWithIdMap()) Public static void LoadData(Map studentMap, Map teacherMap. 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
0 Comments
Leave a Reply. |