package examples; import java.util.*; /** * CS401 Example 32b * * This example is a simple demonstration of the use of wildcards in Generic * Java code. Compare this example with that of ex28.java. * * @author PJ Dillon */ public class ex32b { public static void main(String[] args) { String[] strs = {"transaction", "seriptitious", "sharpener", "Baseball", "perspecacity", "constellation", "Marzipan", "negociation"}; //"parameterize" the Collection declaration Collection collection = new HashSet(); for(int i = 0; i < strs.length; i++) { System.out.println(strs[i]); collection.add(strs[i]); } System.out.println(); printCollection(collection); } /** * prints a Collection to the standard output. We have to look at this in * terms of good generic programming. For the purposes of this program, we * could easily get away with declaring the parameter to be * Collection. But the body of the method really only requires the * objects in the Collection to have a toString() method that we can call, * which all Objects have. Thus, this method can accept a Collection of any * type of object. But, if we declare the parameter as Collection, * then only Collections of type Object can be accepted, making our code above * unable to call the method. This is then a good case for using a wildcard * in the parameter declaration. The syntax below states that this method can * accept a Collection containing objects of any subtype of Object, meaning * any Java objects. * * @param collection Collection to print */ public static void printCollection(Collection collection) { for(Iterator i = collection.iterator(); i.hasNext(); System.out.println(i.next())); System.out.println(); for(Object o : collection) System.out.println(o); } }