我有一个我无法理解的问题..
我正在构建一个 HashMap called wholeSetHistory
.
我正在构建一个 HashMap,它具有与 wholeSetHistory 相同的键和值,称为 wholeSetHistoryT
.
我以类似的方式创建了两个 HashMaps called wholeSetRates, wholeSetRatesT
所有的 HashMap 都是这种格式 HashMap<String, HashMap<String, Double>>
.
我有这个创建火车集的功能
public void createTrainSet(HashMap<String, HashMap<String, Double>> wholeSetRates, HashMap<String, HashMap<String, Double>> wholeSetHistory){
for(String fbid : wholeSetHistory.keySet()){
ArrayList<String> locsBe = new ArrayList<>();
HashMap<String, Double> locss = wholeSetHistory.get(fbid);
HashMap<String, Double> locss2 = wholeSetRates.get(fbid);
for(String loc : locss.keySet()){
if(locss.get(loc)==1.0){
locsBe.add(loc);
}
}
ArrayList<Integer> randomNums = new ArrayList<>();
for(int i=0; i<2; i++){
Random rn = new Random();
int randomNum;
do{
int range = locsBe.size() - 1 + 1;
randomNum = rn.nextInt(range);
}while(randomNums.contains(randomNum));
randomNums.add(randomNum);
locss.put(locsBe.get(randomNum), 0.0);
locss2.put(locsBe.get(randomNum), 0.0);
wholeSetHistory.put(fbid, locss);
wholeSetRates.put(fbid, locss2);
}
randomNums.clear();
}
}
所以,以后我是这样用的
(... creation of wholeSetHistory, wholeSetHistoryT, wholeSetRates, wholeSetRatesT)
System.out.println(wholeSetHistory.get("1"));//1
createTrainSet(wholeSetRatings, wholeSetHistory, nearUserIDWithVisitedTrueValues);
这意味着我仅将参数作为参数传递给函数 wholeSetHistory
虽然,后来我
System.out.println(wholeSetHistory.get("1"));//2
System.out.println(wholeSetHistoryT.get("1"));//3
是这样的:
The values that changes in wholeSetHistory changes in wholeSetHistoryT too! For example, prints 2 and 3 are the same(!) and different from 1.
我很感激任何帮助。
最佳答案
引用指向内存中的一个位置。如果将相同的引用添加到两个不同的数据结构中,则更改一个中的引用也会更改另一个。它们指向内存中的同一个对象。
关于java - HashMap 值在不告诉它们的情况下发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37357220/