2017-04-04 41 views
0

我有一個正在被新對象重用的hashmap的問題,我似乎無法弄清楚如何爲每個新對象提供自己的hashmap。所以本質上來說,當我生成一個時間表並保存它等等時,在創建下一個時間表時,它使用同一個roomList,即某些房間的HashMap的int [] []部分已經被預訂了已從前面的時間表中生成)。我想要的是具有獨特時間表的個人對象,獨特的房間列表和arr。hashmap被新對象重新使用

下面是我的代碼:

首先是產生時間表的人口的類。

public population(int size, boolean init, ArrayList<ListOfObj> arr, HashMap<Room, int[][]> roomList){ 
     listOfTables = new Tables[size]; 
     if(init){ 
      for(int i=0; i<listOfTables.length; i++){ 
       IndivTables indiv; 
       CompleteTable[][][] table = new CompleteTable[5][9][]; 
       indiv = new IndivTables (arr,roomList,table); 
       saveIndiv(i, indiv); 
      } 
     } 
    } 

第二個是創建時間表的實際類。

private CompleteTable[][][] timetable; 
    private HashMap<Room, int[][]> roomList; 
    private ArrayList<listOfObj> arr; 

    public IndivTables (ArrayList<ListOfObj> arr, HashMap<Room, int[][]> roomList, CompleteTable[][][] table){ 
     this.arr = arr; 
     table = generate(arr, roomList); 
     this.timetable = table; 
     this.roomList = roomList; 
    } 

下面是創建時間表的函數。這與IndivTables在同一班。

public static CompleteTable[][][] generate(ArrayList<ListOfObj> arr, HashMap<Room, int[][]> roomList){ 

     int rows = 5; 
     int columns = 9; 
     CompleteTable[][][] timeTable = new CompleteTable[rows][columns][]; 
     HashMap<Room, int[][]> roomListAll = new HashMap<Room, int[][]>(roomList); 

     Random random = new Random(); 

     ListOfObj randomObj; 

     Iterator<ListOfObj > iterator = arr.iterator(); 
     while(iterator.hasNext()){ 

      boolean clash = false; 

      //Get random ListOfObj object 
      randomObj= arr.get(random.nextInt(arr.size())); 

      //Allocate room based on most efficient - doesn't do anything to hashmap 
      Room room = allocateRoom(roomListAll, randomObj, row, column); 
      if(room != null){ 
       CompleteTable comp = new CompleteTable(randomObj, room); 

       if(timeTable[row][column] != null && timeTable[row][column].length>0){ 
        if(!clash){ 
        int[][] val = roomListAll.get(room); 
        val[row][column] = 1; 
        roomListAll.put(room, val); 
       }     
      }else{     
       int[][] val = roomListAll.get(room); 
       val[row][column] = 1; 
       roomListAll.put(room, val); 
       clash = false; 
      } 

      if(!clash){ 
       arr.remove(randomObj); 
      } 
      } 
     } 
    } 
} 
    } 
}  
    return timeTable; 
} 

在此先感謝您的幫助!

+0

當你做'新的IndivTables(arr,roomList,table);'你給每個indivTables你創建相同的HashMap,這就是爲什麼它被重用。 – Ishnark

+0

@Ishnark感謝您的評論,我如何爲每個對象創建一個新的? – michaelskellig510

回答

0

您正在使用相同的散列映射參考在for循環迭代中創建新的IndivTable。因此它使用相同的HashMap。

將以下行新的IndivTables(arr,roomList,表)更改爲 新的IndivTables(arr,new HashMap(),table);然而,如果你想保留roomList的內容,那麼做這個 新的IndivTables(arr,new HashMap(roomList),表);如果你想保留roomList的內容,那麼這個 新的IndivTables

請注意,這是淺拷貝而不是深拷貝。

+0

嗨,謝謝你的回答,但是,這些似乎都不起作用。我仍然使用相同的hashmap。 – michaelskellig510