Generically typed code can be freely used with raw types when attempting to preserve compatibility between non-generic legacy code and newer generic code. 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 can be ignored; at other times, these warnings can denote potentially unsafe operations.
Wiki Markup |
---|
According to the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\], [§4.8 "Raw |
Types,"|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.8] |
The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.
...
Code Block |
---|
List l = new ArrayList(); List<String> ls = l; // Produces unchecked warning |
Wiki Markup |
---|
It is insufficient to rely on unchecked warnings alone to detect violations of this guideline. According to the JLS \[[JLS 2005|AA. Bibliography#JLS 05]\], [§4.12.2.1, "Heap Pollution," |http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#111088] |
Wiki Markup Note that this does not imply that heap pollution only occurs if an unchecked warning actually occurred. It is possible to run a program where some of the binaries were compiled by a compiler for an older version of the Java programming language, or by a compiler that allows the unchecked warnings to suppressed _\[sic\]_. This practice is unhealthy at best.
Wiki Markup |
---|
Extending legacy classes and generifying the overriding methods fails because this is disallowed by the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\]. |
Noncompliant Code Example
...
When executed, this code produces an exception not because a List<String>
receives an Integer
, but rather because the value returned by list.get(0)
is an improper type. In other words, the code throws an exception some time after execution of the operation that actually caused the exception, complicating debugging.
...
This compliant solution enforces type - safety by changing the addToList()
function signature to enforce proper type checking. It also complies by adding a String
rather than an Integer
.
...
The compiler still issues the "unchecked warning," , which may still be ignored. However, the code now fails precisely when it attempts to add the Integer
to the list, consequently preventing the program from proceeding with invalid data.
...
Code Block | ||
---|---|---|
| ||
class BadListAdder {
@SuppressWarnings("unchecked")
private static void addToList(List list, Object obj) {
list.add(obj); // Unchecked warning
}
private 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);
BadListAdder.printOne(d);
System.out.println(i);
BadListAdder.printOne(i);
}
}
|
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 |
Compliant Solution
This compliant solution generifies the addToList()
method, which eliminates any possible type violations.
...
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.
Exceptions
Wiki Markup |
---|
*OBJ10-EX1* Raw types must be used in class literals. For example, because {{List<Integer>.class}} is illegal, it is permissible to use the raw type {{List.class}} \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
Wiki Markup |
---|
*OBJ10-EX2* The {{instanceof}} operator cannot be used with generic types. It is permissible to mix generic and raw code in such cases \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
Code Block |
---|
if(o instanceof Set) { // Raw type
Set<?> m = (Set<?>) o; // Wildcard type
// ...
}
|
Risk Assessment
Mixing generic and non-generic code can produce unexpected results and exceptional conditions.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
OBJ10-J | low | probable | medium | P4 | L3 |
Bibliography
Wiki Markup |
---|
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 23: "Don't use raw types in new code" \[[Bloch 2007|AA. Bibliography#Bloch 07]\] Generics, 1. "Avoid Raw Types in New Code" \[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 88: Raw Deal \[[Darwin 2004|AA. Bibliography#Darwin 04]\] 8.3 Avoid Casting by Using Generics \[[JavaGenerics 2004|AA. Bibliography#JavaGenerics 04]\] \[[JLS 2005|AA. Bibliography#JLS 05]\] [Chapter 5 "Conversions and Promotions"| http://java.sun.com/docs/books/jls/third_edition/html/conversions.html],; also [§4.8 "Raw typesTypes"|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.8] and [§5.1.9 "Unchecked Conversion"|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.9] \[[Langer 2008|AA. Bibliography#Langer 08]\] Topic 3, "[Coping with Legacy|http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#Topic3]" \[[Naftalin 2006|AA. Bibliography#Naftalin 06]\] Chapter 8, "Effective Generics" \[[Naftalin 2006b|AA. Bibliography#Naftalin 06b]\] "Principle of Indecent Exposure" \[[Schildt 2007|AA. Bibliography#Schildt 07]\] "Create a checked collection" |
...