Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics  RSS feed

 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Sheriff
Posts: 23260
124
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You. Now I am clear.
 
Skool. Stay in. Smartness. Tiny ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!