• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Generics

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Eat that pie! EAT IT! Now read this tiny ad. READ IT!
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic