Java hashmap被新对象重复使用
我对被新对象重用的hashmap有一个问题,我似乎不知道如何给每个新对象分配自己的hashmap。因此,基本上,当我生成一个时间表并保存它时,当它要生成下一个时间表时,它使用相同的roomList,即某些房间的hashmap的int[][]部分已经预订(这是从上一个生成的时间表中获取的)。我想要的是一个具有唯一时间表、唯一房间列表和arr的indiv对象 下面是我的代码: 第一个类是生成时间表总体的类Java hashmap被新对象重复使用,java,object,hashmap,int,parameter-passing,Java,Object,Hashmap,Int,Parameter Passing,我对被新对象重用的hashmap有一个问题,我似乎不知道如何给每个新对象分配自己的hashmap。因此,基本上,当我生成一个时间表并保存它时,当它要生成下一个时间表时,它使用相同的roomList,即某些房间的hashmap的int[][]部分已经预订(这是从上一个生成的时间表中获取的)。我想要的是一个具有唯一时间表、唯一房间列表和arr的indiv对象 下面是我的代码: 第一个类是生成时间表总体的类 public population(int size, boolean init, Array
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;
}
public population(int size、boolean init、ArrayList arr、HashMap roomList){
listOfTables=新表[大小];
if(init){
对于(inti=0;i您使用相同的hashmap引用在for循环迭代中创建新的IndivTables。因此它使用相同的hashmap
将以下行新的IndivTables(arr、roomList、table)更改为
新的IndivTables(arr,newhashmap(),table)
但是,如果要保留roomList的内容,请执行此操作
新的IndivTables(arr、新的HashMap(roomList)、table)
请注意,这是浅拷贝而不是深拷贝。当您执行新的IndivTables(arr、roomList、table)时
您为每个indivTables创建了相同的HashMap,这就是它被重用的原因。@Ishnark感谢您的评论,我如何为每个对象创建一个新的HashMap?您好,谢谢您的回答,但是,这些似乎都不起作用。我仍然使用相同的HashMap。
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;
}