java - HashMap 值在不告诉它们的情况下发生变化

标签 java hashmap training-data

我有一个我无法理解的问题..

我正在构建一个 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/

相关文章:

java - 使用 Java 将本地参数传递给 XSLT 中的全局参数

java - Java 中统计文本文件中字符串的出现次数

java - Java HashMap 内部数据结构在重新散列过程中如何变化?

java - JSP中HashMap中的重复键

python - MLP 训练集中的 Scikit 使用列表

lua - torch Lua : Why is my gradient descent not optimizing the error?

java - 通过 JSON Android Java 动态设置选项卡标题

java - 记录器应设置为什么访问级别?

java - Spring 版本自动更改为 3.0.5.RELEASE 尽管我指定了 3.1.0

machine-learning - 训练 SyntaxNet 需要多少数据?