• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

doubt in generics in java 1.5

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
 
Ranch Hand
Posts: 1970
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22862
132
Eclipse IDE Spring TypeScript Quarkus Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic