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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

72Chapter 3An Experienced Programmer’s Introducti<strong>on</strong> to Javaand print the objects in the collecti<strong>on</strong> to the command window. The first iteratoruses the while loop, the sec<strong>on</strong>d <strong>on</strong>e uses a for loop, but they both do thesame thing.As of Java 5.0, there is another way to work your way through a collecti<strong>on</strong>,<strong>on</strong>e that requires less type casting, but more importantly <strong>on</strong>e that can enforcethe type of objects at compile time.Notice in Example 3.14 that the result of the next() is coerced into typeString. That’s because everything coming from the iterator (via the next()method) comes to us as a generic object. That way an iterator can handle anytype of object, but that also means that it is up to the applicati<strong>on</strong> program toknow what type should be coming back from the iterator. Any typecasting errorw<strong>on</strong>’t be found until runtime.With the syntax added in 5.0, not <strong>on</strong>ly is there a shorthand in the forloop for looping with an iterator. There is also syntax to tell the compiler explicitlywhat type of objects you are putting into your collecti<strong>on</strong> or array so thatthe compiler can enforce that type.Example 3.15 may help to make this clearer.Example 3.15 Using a for loop iteratorimport java.util.*;public classForeign{public static voidmain(String [] args){List loa = Arrays.asList(args);System.out.println("size=" + loa.size());for(String str : loa) {System.out.println("arg=" + str);}} // main} // ForeignHere we build a List from the arguments supplied <strong>on</strong> the command line.Notice the type name inside of angle brackets (less-than and greater-than signs).

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

Saved successfully!

Ooh no, something went wrong!