CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
Legacy collections
Untype collection

How to use an untyped collection

  • Code written before Java 5.0 uses untyped collections, which don't use generics to specify the element type.
  • Untyped collections hold elements of type Object.
  • No special coding is required to add objects to an untyped collection.
  • Typically, you must specify a cast to retrieve objects from an untyped collection.
  • The Java 5.0 compiler generates a warning message whenever you add an element to an untyped collection.

Code that stores strings in an untyped array list

// create an untyped array list
ArrayList products = new ArrayList();

// add three productss
products.add(new Product("dctp", "Duct Tape", 4.95));
products.add(new Product("blwr", "Bailing Wire", 14.95));
products.add(new Product("cgum", "Chewing Gum", 0.95));

// print the array list
for (int i = 0; i < products.size(); i++)
{
    Product p = (Product)products.get(i);
    System.out.println(p.getCode() + "\t"
        + p.getDescription() + "\t"
        + p.getFormattedPrice());
}

Resulting output

dctp    Duct Tape       $4.95
blwr    Bailing Wire    $14.95
cgum    Chewing Gum     $0.95

Compiler warnings generated by the code for the untyped array list

H:\Java 1.5\examples\ch10\Untyped Arraylist\UntypedArrayList.java:13: warning:
[unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList
          products.add(new Product("dctp", "Duct Tape", 4.95));
                            ^
H:\Java 1.5\examples\ch10\Untyped Arraylist\UntypedArrayList.java:14: warning:
[unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList
          products.add(new Product("blwr", "Bailing Wire", 14.95));
                            ^
H:\Java 1.5\examples\ch10\Untyped Arraylist\UntypedArrayList.java:15: warning:
[unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList
          products.add(new Product("cgum", "Chewing Gum", 0.95));
                            ^
3 warnings

Tool completed successfully

Previous | Introduction | Untype collection | Wrapper classes