PDA

View Full Version : Function of the for each loop and usage of a TreeSet


The Soul
08-27-2009, 07:12 AM
The for-each loop can be used for many things of which may pertain to fully looping through arrays, ArrayLists, TreeMaps, HashMaps, and more.
A class example:

import java.util.TreeSet;

public class Testing {

public static void main(String[] args) {
TreeSet<String> t = new TreeSet<String>();
t.add("is");
t.add("What");
t.add("tomorrow?");
for (String s : t) {
print(s);
}
}
public static void print(String str) {
System.out.println(str);
}
}

You'd think this class would print out:
is
What
tomorrow?
But it actually prints out:
What
is
tomorrow?

This is because a TreeSet prints things out in order.