• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in generics in java 1.5

 
anveshana bandu
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic