Skip to content

Commit 8b4a426

Browse files
committed
adds an active code for chapter 9.5 and removes pretags to improve readability. issue RunestoneInteractive#19
1 parent c76ed80 commit 8b4a426

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

‎source/ch_9_commonmistakes.ptx‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -105,20 +105,32 @@
105105

106106
<section xml:id="forgetting-to-declare-the-kind-of-object-in-a-container">
107107
<title>Forgetting to declare the kind of object in a container</title>
108+
<program language="java" interactive="activecode">
109+
<code>
110+
// UncheckedWarningDemo.java
111+
import java.util.ArrayList; // Line 2: Import the ArrayList class
112+
113+
public class UncheckedWarningDemo { // Line 4: Class declaration
114+
115+
public static void main(String[] args) { // Line 6: Main method declaration
116+
117+
// This is where the potential for unchecked operations begins.
118+
ArrayList rawList = new ArrayList();//Line 9
119+
120+
rawList.add("Hello");//Line 11: This is the line that will throw an error
121+
122+
System.out.println("Element added: " + rawList.get(0));
123+
} // Line 14: End of main method
124+
} // Line 15: End of class
125+
</code>
126+
</program>
108127
<p>
109128
This is a compiler warning, not an error, indicating a potential type safety issue. It occurs because you are calling the <c>add()</c> method on <c>rawList</c>, which is an <c>ArrayList</c> used as a raw type (i.e., without specifying a generic type like <c>&lt;String&gt;</c> or <c>&lt;Integer&gt;</c>).
110129
</p>
111130

112131
<p>
113132
When <c>ArrayList</c> is used as a raw type, the compiler cannot guarantee the type of elements being added or retrieved, leading to "unchecked" operations. The <c>E extends Object</c> part refers to the generic type parameter <c>E</c> that <c>ArrayList</c> should have, which defaults to <c>Object</c> when the type is not specified, making the <c>add()</c> call unchecked. This can lead to <c>ClassCastExceptions</c> at runtime if incompatible types are later retrieved and cast.
114133
</p>
115-
<pre>
116-
UncheckedWarningDemo.java:8: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList
117-
rawList.add("Hello");
118-
^
119-
where E is a type-variable:
120-
E extends Object declared in class ArrayList
121-
</pre>
122134

123135
</section>
124136
</chapter>

0 commit comments

Comments
 (0)