| Author |
doubt in generics in java 1.5
|
anveshana bandu
Ranch Hand
Joined: Oct 09, 2007
Posts: 42
|
|
Hi All Source:K&B book pgno.577 public class generics { public static void main(String args[]){ List<Integer> myList=new ArrayList<Integer>(); myList.add(4); myList.add(5); Inserter in=new Inserter(); in.insert(myList); } } class Inserter{ void insert(List list){ list.add(new String("42"));///------------>here we should get compilation warning } } According to the statement in the book we should get compilation warning as we added something that is string but when i run the code in jdeveloper it compiled and run with out any warnings.....???how??? please let me know..why i did not get any warning???
|
 |
Peter Chase
Ranch Hand
Joined: Oct 30, 2001
Posts: 1970
|
|
Your class Inserter just takes a plain List, so you can put any type of item into it. Hence the Inserter class compiles fine. The class that uses Inserter is passing a List<Integer> to a method that takes a plain List. I would have expected a compiler warning there. However, inter-class checks of generics are very limited in Java, because generic type information is erased on compilation, and is not available from the class file.
|
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Originally posted by Peter Chase: Your class Inserter just takes a plain List, so you can put any type of item into it. Hence the Inserter class compiles fine.
Actually, I'd expect a warning here, about using a raw List. That's exactly what my Eclipse is doing:
Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized
The class that uses Inserter is passing a List<Integer> to a method that takes a plain List. I would have expected a compiler warning there.
Why? A List<Integer> is still a List, so it is a valid parameter. anveshana, I think you should check your compiler (IDE) settings, I think it is ignoring some warnings it shouldn't ignore.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: doubt in generics in java 1.5
|
|
|