Legacy non-generic example
// Typical Collections usage before Java 5
List greetings = new ArrayList();
greetings.add("We come in peace.");
greetings.add("Take me to your leader.");
greetings.add("Resistance is futile.");
Iterator it = greetings.iterator();
while (it.hasNext()) {
String aGreeting = (String)it.next();
attemptCommunication(aGreeting);
}
// Typical Collections usage before Java 5
List greetings = new ArrayList();
greetings.add("We come in peace.");
greetings.add("Take me to your leader.");
greetings.add("Resistance is futile.");
Iterator it = greetings.iterator();
while (it.hasNext()) {
String aGreeting = (String)it.next();
attemptCommunication(aGreeting);
}
Same example using generics
// Same example using generics.
List<String> greetings = new ArrayList<String>();
greetings.add("We come in peace.");
greetings.add("Take me to your leader.");
greetings.add("Resistance is futile.");
Iterator<String> it = greetings.iterator();
while (it.hasNext()) {
String aGreeting = it.next(); // No downcast.
attemptCommunication(aGreeting);
}
// Same example using generics.
List<String> greetings = new ArrayList<String>();
greetings.add("We come in peace.");
greetings.add("Take me to your leader.");
greetings.add("Resistance is futile.");
Iterator<String> it = greetings.iterator();
while (it.hasNext()) {
String aGreeting = it.next(); // No downcast.
attemptCommunication(aGreeting);
}
0 comments:
Post a Comment