package examples; import java.util.*; /** * CS401 Example 28 * * * * @author PJ Dillon */ public class ex28 { public static void main(String[] args) { String[] strs = {"transaction", "seriptitious", "sharpener", "Baseball", "perspecacity", "constellation", "Marzipan", "negociation"}; /* * Experiment with this changing the types of collection used. With * polymorphism, any collection can we used here and the rest of the code * will work. */ Collection collection = new HashSet(); /* * The foreach loop works for arrays too, as shown in comments here. The * traditional style for loop is used to explicitly show the order in which * the strings are added to the Collection. */ //for(String str : strs) // collection.add(str); for(int i = 0; i < strs.length; i++) { System.out.println(strs[i]); collection.add(strs[i]); } System.out.println(); printCollection(collection); } public static void printCollection(Collection collection) { /* * The two styles of iteration are shown below. The first explicitly * declares an Iterator object and assigns it to the Collection objects * returned iterator. The Collection interface defines this methods, * requiring that all Collections provide some sort of Iterator. The method * returns an iterator that can iterate over the items in the current * Collection. * * The second style shows the use of the new foreach loop to iterate over * each string in the collection without requiring use to declare a separate * iterator object. * * A Collection, in general, and particularly a hashSet implement no * concept of an order to the elements that it stores; conversely, an array * imposes a known ordering based upon the indexing of its elements. Notice * in the output, then, that this will print the strings in a different * order than that in which they were added. The Iterator, though, for both * of the loops shown traverses the Collection in a consistent manner. This * is not guaranteed for the Collection, though, especially as the HashSet * needs to resize itself. */ for(Iterator i = collection.iterator(); i.hasNext(); System.out.println(i.next())); System.out.println(); /* * In order to be as generic as possible, a collection returns references * to the Object class, which is the superclass of any java object. Thus, * a collection can store any java object. This requires us to cast the * object to an instance of whatever type we need. Here, though, we're using * the toString() method of the object; so no cast is necessary. */ for(Object o : collection) System.out.println(o); } }