Originally posted by Paredes Be:
class Generics2{
public static void add(List<? extends Shape> l,int pos, Rect r){
l.add(pos, r); // Compile Error in this line.Why?
}
public static void main(String args[]){
List<ShadedRect> l = new LinkedList<ShadedRect>();
add( l,0, new ShadedRect() );
}
}
Originally posted by Petrus Pelser:
to:
SCJP 5
Hi guys,
Somebody could I tell me, Why in the marked line, cause a compile error "cannot find symbol" if l tends to be a List and it has the add
method?.
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
public static void add(List<? extends Shape> l,int pos, Rect r){
l.add(pos, (ShadedRect)r);
}
Originally posted by joshua antony:
I think once you use ? extends SOMECLASS you are not supposed to add anything to the list.
For adding you can use ? super THE CLASS WHOSE OBJECT YOU WANT TO ADD
Please correct me if I am wrong.
SCJP 5
Originally posted by Pawan preet:
Yes Ankit is right.
Map<? extends Animal,String> map = new HashMap<Cat,String>();
map.put(new Cat(),""); // compiler error
List<? extends Animal> lst = new ArrayList<Cat>();
lst.add(new Cat()); // compiler error
SCJP 5
Originally posted by Pawan preet:
The benefit that you can use it for iteration only but no updates are allowed.
SCJP 5
Originally posted by Keith Lynn:
Of course in each instance of the method, you wouldn't be able to call methods defined only in the subclass on the keys in the Map since there is no way to infer the type.
SCJP 5
What are you doing in my house? Get 'em tiny ad!
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|