Using a generic Iterator to compute the average length of the Strings in a generic Set : generics « Utility Classes « SCJP






import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class MainClass {
  public static void main(String[] argv) {
    Set<String> stringSet = new HashSet<String>();
    stringSet.add("aaaa");
    stringSet.add("a");
    stringSet.add("aa");
    stringSet.add("aaa");

    float totalLengths = 0f;
    Iterator<String> iter = stringSet.iterator();
    while (iter.hasNext()){
      totalLengths += iter.next().length();
    }

  }
}








8.22.generics
8.22.1.When using generic collections, a cast is not needed to get (declared type) elements out of the collection.
8.22.2.Generic Collections
8.22.3.Arguments of all add() calls made on myVec must be of type MyClass or subclasses of MyClass.
8.22.4.You cannot add non-related class to generic collection instance
8.22.5.When retrieving a member of a generic vector, you can reference without casting.
8.22.6.Iterators may be generic.
8.22.7.Sets can be generic.
8.22.8.Using a generic Iterator to compute the average length of the Strings in a generic Set
8.22.9.Maps may be generic.
8.22.10.The Iterators of the Map's keys and values are generic:
8.22.11.Generics and Enhanced For Loops: for (type varable_name : collection)
8.22.12.You can use more than one parameterized type in a single class definition:
8.22.13.Creating Generic Methods