0

我正在尝试打印网络接口列表(最终将它们存储在某种字符串数组中)。以下代码仅在以下情况下打印接口列表

    String[] networkInterfaces = new String[Collections.list(nets).size()];

线不存在。如果该单行不存在,它将打印整个列表。

    Enumeration<NetworkInterface> nets = null;
    try {
        nets = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        e.printStackTrace();
    }
    System.out.println(Collections.list(nets).size());
    String[] networkInterfaces = new String[Collections.list(nets).size()];

    for (NetworkInterface netint : Collections.list(nets)) {
        System.out.println(netint.getName());
    }

抱歉,这个问题没有标签,我不确定什么是合适的。知道为什么会这样吗?我已经对其进行了修改,以便将集合保存到 ArrayList 中(这似乎很好)

    ArrayList<NetworkInterface> netints = Collections.list(nets);

但我仍然很好奇为什么其他方式不起作用。谢谢 :)

4

1 回答 1

4

简而言之,这是因为 anEnumeration是一个有状态的迭代器。

第一次调用时Collections.list(nets),这个库方法将遍历nets枚举,拉出元素,直到枚举不再返回。这按预期工作,返回的列表如您所料。

但是,在下一行您Collections.list(nets) 再次调用。这会从 中提取所有元素nets这些元素现在已用尽,因此“正确”地从没有(更多)元素的枚举中创建了一个空列表。

解决此问题的一种方法是立即转换nets为列表,然后在任何地方引用该列表。因此,您可以将代码的开头更改为:

List<NetworkInterface> nets = null;
try {
    nets = Collections.list(NetworkInterface.getNetworkInterfaces());
}
...

然后只需稍后引用该nets列表,而不是每次都包装一个枚举。

于 2012-10-30T09:08:16.003 回答