Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Generics Warning

 
sentil kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Generics {
static void show(List list){
list.add(new Integer(111));
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
show(list);
}
}
if the legacy code is adding the correct type to list also.
the above code compilation gives warning message.
Please explain this.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that the parameter to the method is a raw List, so even though you're adding an Integer to the list, you could add anything.
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sentil,
The compiler will warn you against the modification of the collection not against the object type added in collection.It will warn you that if you are adding into the collection you can add object of any type.
 
sentil kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if declared parameter type is added, it should not show warning.

if declared parameter type is not added into collection, it can warning message.
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if declared parameter type is not added into collection, it can warning message.

No.It will show Compile time Error

 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even if you will comment the method call // show(list); you will get the warning.So I think whenever you will add any object type to a collection without declaring the collection type you will get the warning for a probable modificaion.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic