【问题标题】:ArrayList<HashMap> returning empty in tests and UI?ArrayList<HashMap> 在测试和 UI 中返回空?
【发布时间】:2016-04-07 19:21:05
【问题描述】:

这是我的代码。我为草率道歉,但本质上它应该做的是模拟交换机使用的向后学习算法。 handleInput 方法接收 src 和 dest MAC 地址和端口号,并将 src MAC 和端口# 作为 HashMaps 添加到 ArrayList 中。整个方法现在没用,因为由于某种原因,没有一个 HashMaps 留在 ArrayList 中。非常感谢任何帮助!

public class Switching {
    ArrayList<HashMap> switchTable = new ArrayList<HashMap>();

    public String handleInput(String srcMacAddress, int portNumber, String destMacAddress){
        String output = "";
        HashMap tableEntry = new HashMap();
        tableEntry.put(srcMacAddress, portNumber);
        for (HashMap hm : switchTable) {
            if (hm.containsKey(destMacAddress)) {
                 output += hm.get(destMacAddress).toString();
            } else {
                 output += "Ports flooded";
            }
        }
        switchTable.add(tableEntry);
        return output;
    }

    public ArrayList<HashMap> getTable(){
        return switchTable;
    }



public class SwitchingTests {
    @Test
    public void testSwitching(){
        new Switching().handleInput("123456", 12, "abcdef");
        ArrayList<HashMap> switchingTable = new Switching().getTable();
        Assert.assertEquals(switchingTable.toString(), "[{123456=12}]");
    }
}

【问题讨论】:

  • 好吧,该方法的第一条指令将 switchTable 替换为一个新的空表......另外,不要使用原始类型。应该是List&lt;Map&lt;String, Integer&gt;&gt;
  • 您能否添加更多代码来使用该类以及预期的输出?

标签: java arraylist hashmap


【解决方案1】:

您正在创建一个Switching 对象并对其调用handleInput(...),然后继续创建一个新的Switching 对象并获取其表。

您需要从已创建的表中获取该表。

public class SwitchingTests {
    @Test
    public void testSwitching(){
        Switching switching = new Switching();
        switching.handleInput("123456", 12, "abcdef");
        ArrayList<HashMap> switchingTable = switching.getTable();
        Assert.assertEquals(switchingTable.toString(), "[{123456=12}]");
    }
}

【讨论】:

  • 啊,对不起,我在排除故障并将类变量声明为 null 并忘记将其更改回来。我仍然有同样的问题。
  • 我明白了。那么我们将需要查看更多关于您如何使用该类的代码,因为这是switchTable 不会保留其内容的唯一明显原因。
  • @trcoats 我用解决您实际问题的方法更新了答案。
【解决方案2】:

在您的 handleInput 方法中,您正在创建新的 switchTable。
你要做的就是改变你的线路
switchTable = new ArrayList() to switchTable = getTable();

【讨论】:

    猜你喜欢
    • 2020-04-30
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    相关资源
    最近更新 更多