• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics doubt

 
Sudhakar Rayavaram
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please have a look at the following class... The complier throws error in the mentioned line... but, i am not able to understand why

public class Wildcards {

public static void main(String[] args) {
List<Shape> data = new ArrayList<Shape>();
update(data);
}

public static void update(Collection<? extends Shape> values) {
values.add(new Shape()); //Compiler error
}

static class Shape {}

static class Circle extends Shape {}

static class Square extends Shape {}
}

The error is:
The method add(capture-of ? extends Wildcards.Shape) in the type Collection<capture-of ? extends Wildcards.Shape> is not applicable for the arguments (Wildcards.Shape).

Thanks,
Sudhakar R
 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Method argument List<? extends Shape > is the reason for error.
this bounded wild card means we cant add anything but null.
can get() Shape only. and can pass List of Subclass of Shape also.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15356
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Sudhakar R", please check your private messages. You can see them by clicking My Profile.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic