Please join us at the new JavaWorld Q&A Forums. Your existing login will work there. The discussions here are now read-only.
Daniel Barbalace
Unregistered
|
|
The whole point of generics is to do compile-time type checking of polymorphic structures. But there is a simple way to get around this compile-time type checking and get a class cast exception at runtime using generics! Ouch.
The following program runs correctly if and only if you comment out the line: listObj.add("bubba");
import java.util.*;
public class TestGenerics {
public static void main (String[] args) { List <Integer> listInt = new LinkedList <Integer>();
List listObj = listInt; listObj.add("bubba"); // Comment out this line to make program work for (int i = 1; i <= 10; i++) listInt.add(i); int x = listInt.get(0); int y = listInt.get(1); System.out.println(x + y); printList(listInt); } public static void printList (List list) { System.out.print("{"); for (Object x: list) System.out.print(x + " "); System.out.print("}"); } }
If the bad line commented out, the output is 3 {1 2 3 4 5 6 7 8 9 10 }
If the bad line is not commented out, the output is Exception in thread "main" java.lang.ClassCastException: java.lang.String at TestGenerics.main(TestGenerics.java:20)
This shows that you can't really trust generics since someone can always lessen the type checking. Unfortunately, that person can also then enhance the type checking like so: List <String> listString = listObj;
Here's a program that gives another ClassCastException: public static void main (String[] args) { List <String> listString = new LinkedList <String>(); for (int i = 1; i <= 10; i++) listString.add("x" + i);
List listObj = listString; List <Integer> listInt = listObj; printSum(listInt); }
public static void printSum (List <Integer> listInt) { int sum = 0; for (Integer x: listInt) sum += x; System.out.println("The sum is " + sum); }
All you get in either programs is a warning about type safety. However, this is not an error and does not stop the compilation. So generics don't give you compile-time type safety. They may help, but they do not solve the problem of ClassCastExceptions for polymorphic structures.
P.S. There really should be a way to use <pre> or <code> tags in these posts. The HTML filter shouldn't filter the <code> tag because doing so causes the code to be misaligned and harder to read.
|
|
0 registered and 1 anonymous users are browsing this forum.
Moderator:
Print Topic
|
Forum Permissions
You cannot start new topics
You cannot reply to topics
HTML is disabled
UBBCode is enabled
|
Rating:
Topic views: 3250
|
|
|
|
|
|
Powered by UBB.threads™ 6.5.5