• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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
reply
    Bookmark Topic Watch Topic
  • New Topic