The following code works however I did not write it. It looks through a computers port names and attempts to match one with a specified string (For RxTx serial communcation).
My question is what that the statement inside the for lo开发者_运维知识库op does? I have never seen any arrangement other then for (initialize;condition test;iterator) statement;
Essentially I'm asking what the (String portName : PORT_NAMES) part does and the the ":" operator does?
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM4", // Windows
};
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
// iterate through, looking for the port
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
Thanks
This is the Java
for-each statement. It justs iterates through every element of the collection specified after the :
sign.
It's what I remember having heard called the "extended for" loop. It's basically the Java equivalent of the C# "foreach" operator; it iterates through the String objects in the PORT_NAMES Enumeration.
EDIT: Linky http://leepoint.net/notes-java/flow/loops/foreach.html
This is the Java for-each construct, which has been familiar since JDK 1.5. It is basically equivalent to this:
for (int i = 0; i < PORT_NAMES.length; ++i) {
String portName = PORT_NAMES[i];
etc...
}
So this is a nicer way to iterate over an array or a collection than having to use an index variable which is not used anywhere else in the loop. For more information see the Oracle documentation:
http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html
精彩评论