Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: tweaked last NCCE/CS

Generically typed code can be freely used with raw types when attempting to preserve compatibility between non-generic legacy code and newer generic code. However, using Using raw types with generic code causes most Java compilers to issue "unchecked" warnings, but still compile the code. When generic and non-generic types are used together correctly, these warnings are not catastrophic, but at other times, these warnings may denote potentially unsafe operations. If generic and non-generic code must be used together, these warnings should not be simply ignored.

...

This noncompliant code example compiles and runs cleanly, because it suppresses the unchecked warning produced by the raw List.add() method. The method printOne() method intends to print the value one, either as an int or as a double depending on the type of the variable type.

...

However, despite list being correctly parameterized, this method prints '1' and never '1.0' because the int value '1' is always added to list without being type checked. This code produces the following output:

Code Block
1.0 
1  
1
1

...

This compliant solution generifies the addToList() method to eliminate , which eliminates any possible type violations.

Code Block
bgColor#ccccff
class GoodListAdder {
  private static <T> void addToList(List<T> list, T t) {
    list.add(t);     // No warning generated
  }

  private static <T> void printOne(T type) {
    if (type instanceof Integer) {
      List<Integer> list = new ArrayList<Integer>();
      addToList(list, 1);
      System.out.println(list.get(0));
    }
    else if (type instanceof Double) {
      List<Double> list = new ArrayList<Double>();

      // This will not compile if addToList(list, 1) is used
      addToList(list, 1.0);

      System.out.println(list.get(0));
    }
    else {
      System.out.println("Cannot print in the supplied type");
    }
  }

  public static void main(String[] args) {
    double d = 1;
    int i = 1;
    System.out.println(d);
    GoodListAdder.printOne(d);
    System.out.println(i);
    GoodListAdder.printOne(i);
  }
}

This code compiles cleanly and runs as expected by printingproduces the correct output:

Code Block
1.0
1.0
1
1

If the method addToList() is externally defined (such as in a library or is an upcall method) and cannot be changed, the same compliant method printOne() can be used, but no warnings result if addToList(1) is used instead of addToList(1.0). Great care must be taken to ensure type safety when generics are mixed with non-generic code.

...