I’m trying to print a list of network interfaces (eventually to store them in a String array of some kind). The following code will only print the list of interfaces if the
String[] networkInterfaces = new String[Collections.list(nets).size()];
line is not there. It will print the entire list if that single line is not there.
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());
}
Sorry for lack of tags on this question, I wasn’t sure what was appropriate. Any idea why this occurs? I’ve modified it such that the collection is saved into an ArrayList (which seems to be fine)
ArrayList<NetworkInterface> netints = Collections.list(nets);
but I’m still curious as to why the other way didn’t work. Thanks 🙂
In short it’s because an
Enumerationis a stateful iterator.The first time that you call
Collections.list(nets), this library method will loop through thenetsenumeration, pulling out elements until the enumeration has no more to return. This works as expected, and the returned list is as you’d expect.However, on the next line you call
Collections.list(nets)again. This pulls all of the elements fromnets, which is now exhausted, and so “correctly” creates an empty list from an enumeration with no (more) elements.One way to fix this problem would be to immediately convert
netsinto a list, and then reference that list everywhere. So you could change the start of your code to:And then just reference the
netslist later on instead of wrapping an enumeration each time.