Enumeration<NetworkInterface> nets
= NetworkInterface.getNetworkInterfaces();
out.print("List of all network interfaces on this machine:\n");
for (NetworkInterface netint : Collections.list(nets)) {
out.printf("name:%s (%s)\n", netint.getName(), netint.getDisplayName());
}
我正在做一项作业,要求我使用 NetworkInterface 列出一堆信息,但我对 Enumeration 不是很熟悉,所以我遇到了麻烦。
我查阅了一些 javadoc 并设法做到了这一点。问题是我需要能够多次浏览列表。
例如,我想使用另一个 for 循环来循环并列出当前启动的所有接口(interface)。
像这样:
for (NetworkInterface netint : Collections.list(nets)) {
if (netint.isUp()) {
out.printf("name:%s (%s)\n", netint.getName(), netint.getDisplayName());
}
}
但是,每当我在第一个循环之后使用 for 循环时,我都没有得到任何输出。我觉得这与我缺乏理解有关。我似乎无法在任何地方找到解释。
最佳答案
无法重置枚举。你的代码不起作用的原因是因为你第一次调用 Collections.list(nets)
“depleats” nets
枚举,所以下一次调用 Collections .list(nets)
产生一个空集合。
为了避免这种情况,从 nets
枚举中收集接口(interface)并迭代结果列表:
List<NetworkInteface> list = Collections.list(nets);
// Iteration 1
for (NetworkInterface netint : list) {
...
}
// Iteration 2
for (NetworkInterface netint : list) {
...
}
关于java - 如何通过枚举列表进行 "reset"迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26148435/