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

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
 
If you two don't stop this rough-housing somebody is going to end up crying. Sit down and read this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic