Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics

 
Akhil Maharaj
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic