Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: edited

Generic code is free to can be freely used with raw types , preserving the compatibility of when attempting to preserve compatibility between non-generic legacy code and newer generic code. However, using raw types with generic code will cause the java compiler most Java compilers to issue "unchecked" warnings. When generic and non-generic code are is used correctly together , these warnings are no threatnot catastrophic, but the same warnings are issued when potentially unsafe operations are performed. If generic and non-generic code must be used together, these warnings should not be simply ignored.

...

This code ordinarily produces an unchecked warning because the raw type of the List.add() method is being used (the list parameter in addToList() method) instead of the parameterized type. To make this compile cleanly, the SuppressWarnings @SuppressWarnings annotation is used.

Code Block
bgColor#FFCCCC

import java.util.*;

public class TestMixedTypes {
  @SuppressWarnings("unchecked")
  publicprivate static void addToList(List list, Object obj) {
    list.add(obj);     // "unchecked" warning
  }
  publicprivate static void print() {
    List<String> list = new ArrayList<String> ();
    addToList(list, 1);
    System.out.println(list.get(0));
  }
  publicprivate static void main(String[] args) {
    TestMixedTypes.print();
  }
}

When run executed, this code will produce produces an exception because list.get(0) is not of the proper type.

Code Block
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
	at TestRaw.print(Test.java:11)
	at TestRaw.main(Test.java:14)

Compliant Solution

By gleaning From the information from this the diagnostic exception message, the error can be quickly resolved by replacing traced to the line addToList(1) in the noncompliant code. Changing this to addToList("1") is unfortunately a superficial defense. To resolve the real issue, use parameterized types consistently and not just abundantly. To enforce compile time checking of types, replace the parameters to addToList with List<String> list and String str. Clearly, the compiler does not allow insertion of an Object once list is parameterized. Likewise, addToList() cannot be called with an argument whose type produces a mismatch.

Code Block
bgColor#ccccff

class Parameterized {
  private static void addToList(List<String> list, String str) {
    list.add(str);     // "unchecked" warning
  }
  private static void print() {
    List<String> list = new ArrayList<String> ();
    addToList(list, "1");
    System.out.println(list.get(0));
  }
  private static void main(String[] args) {
	  Parameterized.print();
  }
}

Noncompliant Code Example

This code reveals the same sort of problem, but it will both compile and run cleanlysuffers from related pitfalls. It compiles and runs cleanly. The method printOne is intended 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 will always print '1' and never '1.0' because the int value 1 is always added to list without being type checked.

Code Block
bgColor#FFCCCC
import java.util.*;

public class TestBadListAdder {
  @SuppressWarnings("unchecked")
  public static void addToList(List list, Object obj) {
    list.add(obj);     // "unchecked" warning
  }
  public static <T> void printOne(T type) {
    if (!(type instanceof Integer || type instanceof Double))
      System.out.println("Cannot print in the supplied type");
    List<T> list = new ArrayList<T> ();
    addToList(list, 1);
    System.out.println(list.get(0));
  }
  public static void main(String[] args) {
    double d = 1;
    int i = 1;
    System.out.println(d); 
    TestBadListAdder.printOne(d);
    System.out.println(i);
    TestBadListAdder.printOne(i);
  }
}

The method printOne is inteded 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 will always print '1' and never '1.0' because the int value 1 is always added to list without being type checked.

The code will produce this outputThis code produces the output:

Code Block
1.0 
1  
1
1

Compliant Solution

If possible, the addToList() method should be generified to eliminate possible type violations.

Code Block
bgColor#ccccff

import java.util.*;

public class TestGoodListAdder {
  public static void addToList(List<Integer> list, Integer obji) {
    list.add(obji);
  }
  public static void addToList(List<Double> list, Double objd) {
    list.add(objd);
  }
  public 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);
    TestGoodListAdder.printOne(d);
    System.out.println(i);
    TestGoodListAdder.printOne(i);
  }
}

This code will compile cleanly and run as expected by printing

Code Block
1.0
1.0
1
1

If 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 as written above, but there will be no warnings 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.

...

Mixing generic and non-generic code may produce unexpected results or program terminationand exceptional conditions.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC10-J

medium

unlikely probable

high

P2 P4

L3

Automated Detection

TODO

...

Wiki Markup
\[[Langer 08|AA. Java References#Langer 08]\] Topic 3, "[Coping with Legacy|http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#Topic3]"
[[Bloch 08|AA. Java References#Bloch 08]\] Item 23: "Don't use raw types in new code"
[[Bloch 07|AA. Java References#Bloch 07]\] Generics, 1. "Avoid Raw Types in New Code"