简体   繁体   中英

hashmap is different outside of while loop

I'm not sure why the hashmap is printing out different things inside this while loop and outside of the while loop. I declared the map outside the while loop, so I assumed that it should be the same inside and outside. In the code, I have the same print statement inside the while loop and outside of it, but they are printing different things. The key for the map is personCounter, which increments and should be unique. Would really appreciate your help.

    public Map<Integer, double[]> setRating(CSVReader r, int taskNum, int taskWeightNumHeader) 
        throws NumberFormatException, IOException {
    String[] line;
    int personCounter = 0;

    Map<Integer, double[]> indivTaskRating = new HashMap<Integer, double[]>();
    while ((line = r.readNext()) != null) {
                    double[] perTaskWeight = new double[5];
        personCounter++;
        int multiplier = taskNum * 5;   
        perTaskWeight[2] = Double.parseDouble(line[taskWeightNumHeader + multiplier]);
        perTaskWeight[1] = Double.parseDouble(line[taskWeightNumHeader + multiplier + 1]);
        perTaskWeight[0] = Double.parseDouble(line[taskWeightNumHeader + multiplier + 2]);
        perTaskWeight[3] = Double.parseDouble(line[taskWeightNumHeader + multiplier + 3]);
        perTaskWeight[4] = Double.parseDouble(line[taskWeightNumHeader + multiplier + 4]);
        indivTaskRating.put(personCounter, perTaskWeight);
        for (int j = 0; j < 5; j ++) {
            System.out.println("personID: " +1+ ", rating: " +indivTaskRating.get(1)[j]);
        }       
    }
    for (int j = 0; j < 5; j ++) {
        System.out.println("personID: " + 1+ ", rating: " +indivTaskRating.get(1)[j]);
    }
    return indivTaskRating;
}

You are using the same double array in every entry you place in the map. At the end it will be populated with the same values for each entry!

You need to reallocate the array on each iteration of your while loop to fix the problem.

while ((line = r.readNext()) != null) {
    double[] perTaskWeight = new double[5];

    // ....
}

You keep reusing the same array, so you actually overwrite its content at each loop (while).

You need to create a new instance ( double[] perTaskWeight = new double[5]; ) within the while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM