Hello,
What does "String a : args" mean in the following code snippet:
public class FindDups {
public static void main(String[] args) {
Set<String> s = new HashSet<String>();
for (String a : args)
if (!s.add(a))
System.out.println("Duplicate detected: " + a);
System.out.println(s.size() + " distinct words: " + s);
}
}
J Leonard
Joe Attardi - 09 Jan 2008 22:20 GMT
> Hello,
>
[quoted text clipped - 10 lines]
> }
> }
It's the new (as of Java 5) for-loop syntax. It iterates over the array
args, assigning each String in the iteration to the variable a.
Basically, this:
for (String a : args) {
...
}
is equivalent to:
for (int n = 0; n < args.length; n++) {
String a = args[n];
...
}
rossum - 09 Jan 2008 23:13 GMT
On Wed, 9 Jan 2008 13:55:22 -0800 (PST),
"John.Leonard@_remove_before_sending_gmail.com"
<John.Richard.Leonard@gmail.com> wrote:
>Hello,
>
[quoted text clipped - 12 lines]
>
>J Leonard
It is a foreach loop, which sets s to each String in args in turn.
Think of it as:
foreach (String s in args) {
doSomethingWith(s);
}
The Java powers that be did not want to mess about with adding new
keywords, so "foreach" stayed as "for" and "in" became ':', so:
for (String s : args) {
doSomethingWith(s);
}
rossum