we havelist1.add( new Animales)
that mean we can addList< ? super Dog>
Dog
andAnimales
Object
adil zahir wrote: we have
that mean we can addList< ? super Dog>
Dog
andAnimales
Object
can you explain me why i have this Error ?
Can you explain to us why you think that a List<? super Dog> should be able to add Dog, Animales, and Object? ... because that is not true.
Henry
andAnimales
but we can addObject
Dog
that mean evrything super DogList<? super Dog>
adil zahir wrote:
so for that i want knew why ?!!! because we havethat mean evrything super DogList<? super Dog>
add.( new Animales() )
?x IS-A Dog, x IS-A Animales, and x IS-A Object
adil zahir wrote:Henry Wong,
what i understand we can't doadd.( new Animales() )
because the object " new Animales() " not satisfied " the 3 rules?x IS-A Dog, x IS-A Animales, and x IS-A Object
Siddharth Raja wrote:This is allowed:
List<Animal> L = new ArrayList<Animal>();
L.add(new Dog()); L.add(new Animal());
This is NOT Allowed:
List<? super Dog> L = new ArrayList<Animal>();
L.add(new Dog());
L.add(new Animal()); //COMPILATION ERROR!
now i understand that due to 'type erasure' JVM does not have info of what type of List its dealing with, so the compiler has to be strict.
Siddharth Raja wrote: But here the compiler knows the ArrayList is of type 'Animal' since we are initializing it that way.
But here's a twist....later on in the code someone could reassign L as follows: L = new ArrayList<Dog>(); (the compiler will have to permit this since L is <? super Dog>)
now L.add(new animal()) is obviously going to blow up the prog since L is of type Dog
SO, im guessing that this is the main reason that L.add(new Animal()) is being disallowed.....possible conversion (by re assigning) to Dog (subtype)
Am i correct?
Siddharth Raja wrote:"There is nothing in the Java Language Specification that mentions any determination of the type by its usage"
i'm talking about compile time
so then why are these wrong?
List<? extends Dog> L = new ArrayList<Animal>();
or
List<String> L = new ArrayList<Integer>();
and so on...
Siddharth Raja wrote:
also my basic point was this (lets forget type erasure and everything else irrelevant): since there's a possibility that L = new ArrayList<Dog>(); can be done later, thereby reassigning L, there's a danger of letting objects of type Animal get added to L. the compiler 'anticipates' this and doesn't let Animal objs get added to the List.
Am i correct in assuming this?
If not then why? whats wrong with this point please?
I think he's gonna try to grab my monkey. Do we have a monkey outfit for this tiny ad?
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|