File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics" Watch "Generics" New topic
Author

Generics

Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62
Hello,

I am studying generics.

Code Snippet#1


Error Message:
cannot find symbol
symbol : method add(java.lang.String)
location: interface java.util.List<java.lang.Integer>
l.add("hello");
^

Code Snippet#2


Code Snippet#1 flags a compilation error, while Code Snippet#2 compiles and runs. I fail to understand why and difference between the two declarations of the list l.

Thanks for help in advance.


SCJP6
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18507
    
  40


In the first case, you assigned an object that doesn't use generics to a reference that does -- hence the warning. Then you tried to add a string to a list that can only take integer (based on the reference) -- hence, the error.

In the second case, you assigned an object that uses generic to a reference that does not -- hence the warning. Then you tried to add a string to a list that doesn't use generics (based on the reference) -- which is perfectly fine.

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62
Thank You. Now I am clear.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics
 
Similar Threads
generics doubt
Generics question
Generics
Generics
Generics