13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.2 Fundamental Language Elements73This is the new syntax that tells the compiler that we are putting Strings intothe List. The compiler will enforce that and give a compile time error if wetry to add any other type to the List.Now we come to the for loop. Read it as “for str in loa” or “for Stringvalues of str iterating over loa.” We will get an iterator working out of sightthat will iterate over the values of loa, our List. The values (the result of thenext() method) will be put in the String variable str. So we can use strinside the body of the loop, with it taking <strong>on</strong> successive values from thecollecti<strong>on</strong>.Let’s describe the syntax, then, asfor ( SomeType variable : SomeCollecti<strong>on</strong>Variable ) {}which will define variable to be of type SomeType and then iterate over theSomeCollecti<strong>on</strong>Variable. Each iterati<strong>on</strong> will execute the body of the loop,with the variable set to the next() value from the iterator. If the collecti<strong>on</strong> isempty, the body of the loop will not be executed.This variati<strong>on</strong> of the for loop works for arrays as well as for these newtyped collecti<strong>on</strong>s. The syntax for arrays is the same. Example 3.16 will echo thearguments <strong>on</strong> the command line, but without loading up a List like we didin our previous example.Example 3.16 A for loop iterator for arraysimport java.util.*;public classForn{public static voidmain(String [] args){for(String str : args) {System.out.println("arg="+str);}} // main} // Forn

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!