Failed test case, what am I doing wrong?

我与影子孤独终老i 提交于 2019-12-06 11:18:55

I think the main problem is you are modifying and inserting the same ArrayList instance for each state. A simple version, without robustness checking might be:

    TreeMap<String, ArrayList<Double>> map = new TreeMap<>();
    while (dataSource.hasNext()) {
        String state = dataSource.next();
        Double d = Double.parseDouble(dataSource.next());
        map.computeIfAbsent(state, k -> new ArrayList<>()).add(d);
    }
    return map;

The computeIfAbsent allows you to add a new ArrayList when you see a new state (Java 8+).

Another issue is the assertEquals. Since the expected number list data is in a different order than the actual, the ArrayLists are not equal. You could verify the keys and values like this:

    assertEquals(expected.keySet(), actual.keySet());
    expected.forEach((state, list) -> {
        Collections.sort(list);
        Collections.sort(actual.get(state));
        assertEquals(list, actual.get(state));
    });

Your code clears statePopData every time there is a new string, so even if you see:

California 1
California 2
California 3

You will only wind up with a map that says California: 3, as map.put() will replace the current value for the key "California" with whatever you provide it.

You need to recall the current version of the state's array each time you see that state, and then append the new data to the array before you re-insert that .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!