aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding Generics Warning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding Generics Warning" Watch "Regarding Generics Warning" New topic
Author

Regarding Generics Warning

sentil kumar
Ranch Hand

Joined: Oct 23, 2006
Posts: 74
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Nov 01, 2006
Posts: 381
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.


~Sanjeev Singh<br />SCJP 1.5
sentil kumar
Ranch Hand

Joined: Oct 23, 2006
Posts: 74
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

Joined: Mar 02, 2005
Posts: 580
if declared parameter type is not added into collection, it can warning message.

No.It will show Compile time Error

Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Regarding Generics Warning