【问题标题】:System.out.print producing correct result but looping through HashMap is notSystem.out.print 产生正确的结果,但循环通过 HashMap 不是
【发布时间】:2016-03-24 12:14:34
【问题描述】:

我正在制作一个“通用”灯具生成器。因此,您输入名称/球队等,它会创建一个需要播放的赛程表。

当“团队”输入时,它们被输入到一个hashmap中,int的原因是每个团队都有点,所以每个人都默认为0。

我正在尝试创造一种方法,让每个人都能互相吟诵一次,我可以通过这种方法做到这一点。

public HashMap<String, String> genFixtures(HashMap<String, Integer> m_playerList){
    HashMap<String, String> r_fixtures = new HashMap<String, String>();

    ArrayList<String> m_fixtures = new ArrayList<String>();
    for (String key : m_playerList.keySet()){
        m_fixtures.add(key);
    }

    for (int i = 0; i < m_fixtures.size(); i++){
        for (int j = i + 1; j < m_fixtures.size(); j++){
            if (m_fixtures.get(i).equals(m_fixtures.get(j))){
                continue;
            } else {
                r_fixtures.put(m_fixtures.get(i) , m_fixtures.get(j));
            }

        }
    }
    return r_fixtures;
}

这将创建一个带有字符串键和值的新哈希图,因为我希望哈希图存储每个团队,键是一个团队,值是一个团队(我觉得这是一种非常糟糕的方法)。 然后,我将原始 String,Int Hashmap 的所有键添加到 ArrayList,执行一个操作,使它们相互匹配,完全按计划工作,然后将它们添加到该 String String hashmap 并返回到此方法中单独的类:

 if(e.getSource()== m_generate){
    HashMap<String, String> m_gend = new HashMap<String,String>();
    m_gend =  m_fix.genFixtures(m_playerList);
    for(Map.Entry<String, String> entry : m_gend.entrySet()) {
        String m_key = entry.getKey();
        String m_value = entry.getValue();
        m_labelNames.setText(m_labelNames.getText() + m_key + " v " + m_value + "\n");
        }
    }

但是当我将 hashmap 的内容添加到 JTextArea 时,假设我添加了团队“Ceri”、“Harry”、“Matthew”。 输出的是

马修诉哈利 塞里诉哈利

但没有 Ceri v Matthew。

【问题讨论】:

    标签: java string arraylist hashmap


    【解决方案1】:

    当我将 hashmap 的内容添加到 JTextArea 时,让我们说 我添加了团队“Ceri”、“Harry”、“Matthew”。输出的是

    Matthew v Harry Ceri v Harry

    因为Hashmap 不保留插入顺序。当您迭代 Hashmap 条目时,您将获得不同的不同值

    你可以在文档中找到它

    这个类不保证地图的顺序;在 特别是,它不保证订单将保持不变 随着时间的推移

    来自Oracle documention

    【讨论】:

    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2020-12-14
    • 2015-10-12
    • 2015-01-06
    • 2017-05-06
    • 2018-09-23
    相关资源
    最近更新 更多