Search code examples
javatreemap

TreeMap values getting overridden


I have a treemap which has string as the key and arraylist of integers as the values. I added two values to the treemap. When I add first value to the treemap it was correct. When I add the second value, the values associated with the first key are changed. Both keys are pointing to the same arraylist.

        while (resultSet.next()) {
            firstName = resultSet.getString(1);
            lastName = resultSet.getString(2);
            scores.add(Integer.parseInt(resultSet.getString(4)));
            while (resultSet.next()) {
                String firstName1 = resultSet.getString(1);
                String lastName1 = resultSet.getString(2);
                if (firstName1.equalsIgnoreCase(firstName) && lastName1.equalsIgnoreCase(lastName)) {
                    scores.add(Integer.parseInt(resultSet.getString(4)));
                } else {
                    resultSet.previous();
                    break;
                }
            }
            if (!studentScores.containsKey(firstName + lastName)) {
                studentScores.put(firstName + lastName, scores);
            }
            for (int i = 0; i < scores.size(); i++) {
                scores.remove(i);
            }
        }

Solution

  • Values are getting replaced as you are adding and then removing the same array list for each of the firstName+lastName combination.

    Replacing the for loop with score = new ArrayList(); should fix the issue.