更新特定的HashMap键值

时间:2017-03-20 21:51:43

标签: java object hashmap

我正在尝试更新特定的HashMap键值,但是,我正在为所有键值更新正在更新的值。我有一个关键类型房间的HashMap(我自己的类)和一个2D int数组的值,表示房间的可用性。

我有一个Room对象,这是我要更新的房间(键)。功能分配空间并不重要,它只是根据特定标准分配房间。

行和列只是2D数组中应该更新的位置。但是,此位置的所有键值都在更新,而不是仅更新一个特定的键值。

有谁能请说明我出错的地方? 提前谢谢!

生成listOfRooms的方式:

//Rooms are added to the list as such
listOfRooms.add(new Room ("001", 72, "Lecture", "YY"));

//This function is called which adds the room and an int 2D array to a hash map
public HashMap<Room,int[][]> finaliseRooms(){ 
    int[][] roomAvailability = new int[][]{ 
        {0,0,0,0,0,0,0,0,0}, 
        {0,0,0,0,0,0,0,0,0}, 
        {0,0,0,0,0,0,0,0,0}, 
        {0,0,0,0,0,0,0,0,0}, 
        {0,0,0,0,0,0,0,0,0} }; 
     for(Room room : listOfRooms){ 
        finalListOfRooms.put(room, roomAvailability); 
     } 
     return finalListOfRooms;
}

更改特定键的值(此时,listOfRooms已等同于返回值finalListOfRooms):

//This is where I try to change the value of a specific key
HashMap<Room, int[][]> a = new HashMap<Room, int[][]>(listOfRooms);
Room bestRoom = allocateRoom(a, randomMLSC, row, column);

String building = bestRoom.getRoomBuilding().toString();
String roomnum = bestRoom.getRoomNumber().toString();

for(Map.Entry<Room, int[][]> entry : a.entrySet()){
   if(entry.getKey().getRoomBuilding().toString().equals(building)){
       if(entry.getKey().getRoomNumber().toString().equals(roomnum)){
            int[][] val = entry.getValue();
            if(val[row][column]==0){
               val[row][column] = 1;
            }
        }   
    }
}

allocateRoom:

public Room allocateRoom(HashMap<Room, int[][]> listOfRooms, ModuleLecturerStudentCombination mlsc, int row, int column){
        ArrayList<Room> availableRooms = new ArrayList<Room>();

        for(Map.Entry<Room, int[][]> entry : listOfRooms.entrySet()){
            int[][] av = entry.getValue();
            if(av[row][column]==0){
                availableRooms.add(entry.getKey());
            }
            //goes on to do more stuff, not with listOfRooms
        }
}

1 个答案:

答案 0 :(得分:1)

finaliseRooms方法中,您为每个键分配相同的数组,这意味着当一个条目更改时,所有条目都将更改。您应该在每个循环中移动roomAvailability的声明。