Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2008

Tip: Looking for answers? Try searching our database.

JAVA lang question.

Thread view: 
John.Leonard@_remove_before_sending_gmail.com - 09 Jan 2008 21:55 GMT
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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.