Generically typed code can be freely used with raw types when attempting to preserve compatibility between non-generic nongeneric 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 nongeneric 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] \[[JLS 2005|AA. Bibliography#JLS 05]\]: |
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.
If When a parameterized type tries to access an object that is not of the parameterized type, heap pollution occurs. For instance, consider the following code snippet below.
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 rule. According to the _Java JLS \[[JLS 2005|AA. Bibliography#JLS 05]\], Language Specification_, [§4.12.2.1, "Heap Pollution," |http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#111088] \[[JLS 2005|AA. Bibliography#JLS 05]\]: |
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.
Extending legacy classes and generifying making the overriding methods generic fails because this is disallowed by the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\]. Wiki Markup
Noncompliant Code Example
This noncompliant code example compiles although it but produces an unchecked warning because the raw type of the List.add()
method is used (the list
parameter in the addToList()
method) rather than the parameterized type.
Code Block | ||
---|---|---|
| ||
class MixedTypes { private static void addToList(List list, Object obj) { list.add(obj); // unchecked warning } public static void main(String[] args) { List<String> list = new ArrayList<String> (); addToList(list, 1); System.out.println(list.get(0)); } } |
When executed, this code produces throws an exception. This happens not because a List<String>
receives an Integer
but because the value returned by list.get(0)
is an improper type (an Integer
rather than a String
). In other words, the code throws an exception some time after the execution of the operation that actually caused the exceptionerror, complicating debugging.
...
This compliant solution enforces type safety by changing the addToList()
method signature to enforce proper type checking. It also complies by adding a String
rather than an Integer
.
Code Block | ||
---|---|---|
| ||
class Parameterized { private static void addToList(List<String> list, String str) { list.add(str); // No warning generated } public static void main(String[] args) { List<String> list = new ArrayList<String> (); addToList(list, "1"); System.out.println(list.get(0)); } } |
The compiler does not allow prevents insertion of an Object
once list
is parameterized. Likewise, to the parameterized list
because addToList()
cannot be called with an argument whose type produces a mismatchwith an argument whose type produces a mismatch. This code has consequently been changed to add a String
to the list instead of an Integer
.
Compliant Solution (Legacy Code)
While the previous compliant solution eliminates use of raw collections, this could it may be infeasible to implement this solution when interoperating with legacy code.
...
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.
...
This noncompliant code example compiles and runs cleanly because it suppresses the unchecked warning produced by the raw List.add()
method. The printOne()
method intends to print the value one1, 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:
...
This compliant solution generifies the addToList()
method, which eliminates eliminating any possible type violations.
...
If the method addToList()
is externally defined (such as in a library or as 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 nongeneric code.
Exceptions
Wiki Markup |
---|
*OBJ03-EX0* Raw types must be used in class literals. For example, because {{List<Integer>.class}} is illegalinvalid, it is permissible to use the raw type {{List.class}} \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
...
Risk Assessment
Mixing generic and non-generic nongeneric code can produce unexpected results and exceptional conditions.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ee01e990113a0fcc-cd245f77-40044983-b86699e8-5d75626614b79df4bf215cd2"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. Bibliography#Bloch 08]] | Item 23: ". Don't use raw types in new code " | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f3307fe6440e8169-bad1368a-4bc24d70-944f9ec9-96ac717da020875438257dd7"><ac:plain-text-body><![CDATA[ | [[Bloch 2007 | AA. Bibliography#Bloch 07]] | Generics, 1. " Avoid Raw Types in New Code" raw types in new code | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ecfccc425023b4bc-0ca46291-47d24371-86c9a0c2-eeb662ae24c8a613291dfd43"><ac:plain-text-body><![CDATA[ | [[Bloch 2005 | AA. Bibliography#Bloch 05]] | Puzzle 88: . Raw Deal | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="639a6d99e58626f6-92ea9ef8-4f7f4918-9550a5d3-2da066329b5081b5311ba2b2"><ac:plain-text-body><![CDATA[ | [[Darwin 2004 | AA. Bibliography#Darwin 04]] | 8.3, Avoid Casting by Using Generics | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="df23e8124811b0d1-1b1efc6f-4d6947d3-9c21a54c-5d89ceee1773ba6642cf8f70"><ac:plain-text-body><![CDATA[ | [[JavaGenerics 2004 | AA. Bibliography#JavaGenerics 04]] |
| ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b55fa6e6f452cc5c-f4aac907-40654c80-a32fb088-24ac91ca185918545663878d"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | [Chapter 5 ", Conversions and Promotions" | http://java.sun.com/docs/books/jls/third_edition/html/conversions.html] | ]]></ac:plain-text-body></ac:structured-macro> |
| |||||
| |||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="091152d8a8f39d96-76433093-4e834eaa-8018a484-ff3bf39d60e1875bd83a40f7"><ac:plain-text-body><![CDATA[ | [[Langer 2008 | AA. Bibliography#Langer 08]] | Topic 3, " [Coping with Legacy | http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#Topic3] " | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d52da01d6b2ea5a7-3caee9a3-465946de-ab079082-ef13b15c9084ab5aef426871"><ac:plain-text-body><![CDATA[ | [[Naftalin 2006 | AA. Bibliography#Naftalin 06]] | Chapter 8, " Effective Generics " | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="08028220e41c6d60-05cefb38-402a4b90-9b2ea297-66536b5a200fe1e9191c8511"><ac:plain-text-body><![CDATA[ | [[Naftalin 2006b | AA. Bibliography#Naftalin 06b]] | " Principle of Indecent Exposure " | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="49ddb921d875ec3d-4070aa0e-483d4bb3-bb13bfa8-dff18cd39492735394a10f1c"><ac:plain-text-body><![CDATA[ | [[Schildt 2007 | AA. Bibliography#Schildt 07]] | " Create a checked collection " | ]]></ac:plain-text-body></ac:structured-macro> |
...