wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics 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 "Generics" Watch "Generics" New topic
Author

Generics

Akhil Maharaj
Ranch Hand

Joined: Sep 29, 2007
Posts: 63
Hi ,

Can any body throw some light on why I am getting error at line 1 and compile warning on line 2 in the following code

import java.util.* ;
class A {

public static void main(String[] args) {



List<?> myList = new ArrayList();
method1(myList);
myList.add(new Integer(10)); // Line 1 //COMPILER ERROR .


method2(myList); // Line 2 // COMPILER WARNING


}

static void method1(List x){



}

static void method2(List x){

x.add(new Integer(20));

}
[ October 09, 2007: Message edited by: Akhil Maharaj ]
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
When you have a List<?> then it is read-only. You cannot add anything to that list, because it is not sure what parameterized type it actually has.

Yours,
Bu.
Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 278
Compiler Error 1 comes because you declared list as List<?>
which says list of any type.In wild cards,we canont anything except null.
So add(object) fails

Compiler warning 2 comes because method2()called is adding something to the generic-based list.Here whenever generic -code is mixed with non-generics code and you try to add something ,which is legal and can fail later,compiler warnings.
Check K & B SCJP pg 576
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics