Why cannot write in covariance in Java? [duplicate] - java

This question already has answers here:
What is a difference between <? super E> and <? extends E>?
(10 answers)
Closed 4 years ago.
I have code like this:
class Scratch {
public static void main(String[] args) {
List<Cat> cats = new ArrayList<>();
List<? extends Animal> animals = cats;
animals.add(new Cat()); // compile error
Animal animal = animals.get(0);
}
}
class Animal {
}
class Cat extends Animal {
}
class Dog extends Animal {
}
Why cannot add a Cat instance to animals? Add Cat instance or Dog instance to animals, and read elements as animal is type safe. I know PECS (short for "Producer extends and Consumer super"), but I can't understand that why can't write in covariance and cant't read in contravariance in Java.

<? extends Animal> is not Cat, it can be any subclass ot Animal, for example:
List<? extends Animal> dogs = new ArrayList<Dog>();
dogs.add(new Cat()); // compile error
No matter what actually type <? extends Aminal> is, it can't add any subclass of Animal. Use List<Animal> instead of List<? extends Animal>.

Related

How to use List<? extends >? [duplicate]

This question already has answers here:
How can I add to List<? extends Number> data structures?
(7 answers)
Difference between <? super T> and <? extends T> in Java [duplicate]
(14 answers)
Closed 10 months ago.
I want to list.addAll, but get a error,
what should I do?
The code as follow
public class Animal {
private void speak(){
System.out.println("Animal");
}
protected void name(){
System.out.println("name");
}
}
public class Dog extends Animal{
public void test(){
super.name();
speak();
}
private void speak(){
System.out.println("dog");
}
}
public class Test {
public static void main(String[] args) {
Dog dog = new Dog();
dog.test();
List<? extends Animal> animals = new ArrayList<>();
List<Dog> dogs = new ArrayList<>();
dogs.add(new Dog());
dogs.add(new Dog());
//TODO this is error
animals.addAll(dogs);
}
}
the error as follow
Required type: Collection <? extends capture of ? extends Animal>.
Provided: List< Dog >.

not able to add Animal object with wildcard super of Dog [duplicate]

This question already has answers here:
What is PECS (Producer Extends Consumer Super)?
(16 answers)
Closed 12 months ago.
Had seen many examples related to use of super wildcard. Majority of them are with Number and Integer classes. However for my understanding I was trying the below code:
package util;
import java.util.*;
class Animal{
void eat() {
System.out.println("animal eats");
}
}
class Dog extends Animal{
void eat() {
System.out.println("dog eats");
}
}
class Cat extends Animal{
void eat() {
System.out.println("cat eats");
}
}
public class Test {
public void addAnimal(List<? super Dog> list) {
list.add(new Animal());//******* getting error here
list.add(new Dog());
}
public static void main(String[] args) {
List<? super Dog> lsDogs = new ArrayList<Dog>();
List<? super Dog> lsAnimals = new ArrayList<Animal>();
}
}
as per the docs which I have understood super means we can add anything that is on right hand side or its super class. Here I created Dog class which extends Animal class. I can only add Dog type of objects and not Animal. Why is it not possible.. any specific reasons
List<? super Dog> says "this is a List that you can add a Dog to. You might be able to add a Dog because it is a List<Dog>, because it's a List<Animal>, or because it's a List<Object>."
You can't add an Animal to a List<? super Dog>, because your Animal could be any Animal subclass, e.g. a Cat, and then you may have a Cat in a List<Dog>.
class Animal { void sound() {}}
class Cat extends Animal {}
class Dog extends Animal {}
class Test {
public static void main(String[] args) {
List<Object> objects = new ArrayList<>();
List<Animal> animals = new ArrayList<>();
List<Dog> dogs = new ArrayList<>();
List<Cat> cats = new ArrayList<>();
add(objects);
add(animals);
add(dogs);
add(cats); // Error, must be a list we can add Dogs to
addAnimal(objects);
addAnimal(animals);
addAnimal(dogs); // Error, must be a list which can contain any Animal
useList(objects); // Error, must be a List of Animals
useList(animals);
useList(dogs);
useList(cats);
}
public static void add(List<? super Dog> list) {
list.add(new Dog());
}
public static void addAnimal(List<? super Animal> list) {
list.add(new Dog());
list.add(new Cat());
for (Animal a : list) { // error, ? can be Object
a.sound();
}
}
// If we're consuming items from the list we use extends
public static void useList(List<? extends Animal> list) {
list.add(new Animal()); // error, ? is a specific but unknown subclass of Animal
for (Animal a : list) {
a.sound();
}
}
}
The ? means that we don't know what the class is but it is a definite class.
? super of Dog means that ? is something that is a parent of dog. For your example you have { Object, Animal, Dog }. So your ? can be any of those 3 classes.
You can add to the list as long as what every you add can be cast to ?.
Can you add a Dog to the list? Yes because Dog can be cast to any Object, Animal, Dog.
Can you add an Animal to the list? No, because Animal cannot be cast to Dog.
Since Dog is the most specified it is the boundary that we compare against. You can add any Dog or class that extends Dog.

Abstract List<Person>

Update: My classes are more complex than this, I just am stuck on the ArrayList line
I have the following classes:
class CatList {
List<Cat> cats = new ArrayList<Cat>();
}
and
class DogList {
List<Dog> dogs = new ArrayList<Dog>();
}
Where Cat and dog are both data classes.
but I want to create an abstract class:
abstract class AnimalList {
List<???> animals;
AnimalList(Class animal) {
animals = new ArrayList<???>();
}
}
so that I can inherit my classes
AnimalList CatList = new AnimalList(Cat);
AnimalList DogList = new AnimalList(Dog);
AnimalList CowList = new AnimalList(Cow);
Hopefully that makes more sense. My question is therefore What are the ??? bits?
Using a type parameter might solve your problem - using the same class for different types - without inheritance:
public class AnimalList<T> {
private List<T> list = new ArrayList<T>();
public void add(T animal) {
list.add(animal);
}
// more methods
}
Now you can parametize instances for persons and animals:
AnimalList<Cat> catList = new AnimalList<Cat>();
catList.add(new Cat());
AnimalList<Dog> dogList = new AnimalList<Dog>();
dogList.add(new Dog());
My advice is, to create a base class for Dog and Cat, let's say Animal. This way you spare yourself some time, because you don't have to write the same methods and members in both classes, and it works like this:
public (abstract) class Animal
{
members and functions, that both Cats, and Dogs have...
}
then inherit from Animal like this:
public class Cat extends Animal
{
...
}
From now on you can create an ArrayList like this:
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Cat());
animals.add(new Dog());
If you want to create an AnimalList anyway, then your best option is Andreas's solution, generics are meant for these kind of situation.
IF you know, how inheritance works, and you already considered building your application like this, then sorry for my post!
As was said, you might want to define a base class Animal for Cat and Dog and then:
class AnimalList<T extends Animal> {
private List<T> animals;
protected AnimalList() {
animals = new ArrayList<T>();
}
}
If you need to pass the Class you might wand to define yje constructor as:
AnimalList(Class<T> type) { … }
If you need to handle some AnimalList for some unknown Animal type you might use:
private AnimalList<? extends Animal> list;

Java Generics: adding wrong type in collection

Who could me explain this?
I have these couple of classes:
abstract class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
public void woof() {
System.out.println("woof");
}
}
class Cat extends Animal {
public void meow() {
System.out.println("meow");
}
}
And this is the action:
import java.util.ArrayList;
import java.util.List;
public class TestClass {
public static void main(String[] args) {
new TestClass().go();
}
public void go() {
List<Dog> animals = new ArrayList<Dog>();
animals.add(new Dog());
animals.add(new Dog());
doAction(animals);
}
public <T extends Animal> void doAction(List<T> animals) {
animals.add((T) new Cat()); // why is it possible?
// Variable **animals** is List<Dog>,
// it is wrong, that I can add a Cat!
for (Animal animal: animals) {
if (animal instanceof Cat) {
((Cat)animal).meow();
}
if (animal instanceof Dog) {
((Dog)animal).woof();
}
}
}
}
This example compile without errors, and output is:
woof
woof
meow
But how can I add in list of Dog a Cat? And how the Cat is casted to Dog?
I use:
java version "1.6.0_24". OpenJDK Runtime Environment (IcedTea6 1.11.1) (6b24-1.11.1-4ubuntu3)
Ok here's the deal with generics (anything that uses casting hackery might not be safe at runtime, because generics work by erasure):
You can assign a subtype parameterised the same way e.g
List<Animal> l = new ArrayList<Animal>();
and you can add items that are the type of this parameter or its subclasses e.g
l.add(new Cat());
l.add(new Dog());
but you can only get out the type of the parameter:
Animal a = l.get(0);
Cat c = l.get(0); //disallowed
Dog d = l.get(1); //disallowed
Now, you can use a wild card to set an upper bound on the parameter type
List<? extends Animal> l = new ArrayList<Animal>();
List<? extends Animal> l = new ArrayList<Cat>();
List<? extends Animal> l = new ArrayList<Dog>();
But you can't add new items to this list
l.add(new Cat()); // disallowed
l.add(new Dog()); // disallowed
In your case you have a List<T> so it has a method add(T t) so you can add if you cast to T. But T has type bounded above by Animal so you shouldn't even be trying to add to this list, but it is treated as a concrete type and that's why it allows the cast. However this may throw a ClassCastException.
And you can only retrieve items that are the upper bound type
Animal a = l.get(0);
Cat c = l.get(0); //disallowed
Dog d = l.get(1); //disallowed
Or you can set the lower bound parameter type
List<? super Animal> l1 = new ArrayList<Object>();
List<? super Animal> l1 = new ArrayList<Animal>();
List<? super Cat> l2 = new ArrayList<Animal>();
List<? super Cat> l2 = new ArrayList<Cat>();
List<? super Dog> l3 = new ArrayList<Animal>();
List<? super Dog> l3 = new ArrayList<Dog>();
And you can add objects that are subtypes of the lower bound type
l1.add(new Cat());
l1.add(new Dog());
l1.add(new Object()); //disallowed
But all objects retrieved are of type Object
Object o = l1.get(0);
Animal a = l1.get(0); //disallowed
Cat c = l2.get(0); //disallowed
Dog d = l3.get(0); //disallowed
Do not expect generics to perform runtime type checking. During compilation, Java performs all the type inference, instantiates all the types, ... and then erases all trace of generic types from the code. At runtime, the type is List, not List< T > or List< Dog >.
The main question, why it allows you to cast new Cat() to type T extends Animal, with only a warning about unchecked conversions, is valid. Certain unsound features of the type system make legalizing such dubious casts necessary.
If you want the compiler to prevent the addition of anything to the list, you should use a wildcard:
public void doAction(List< ? extends Animal > animals) {
animals.add(new Cat()); // disallowed by compiler
animals.add((Animal)new Cat()); // disallowed by compiler
for (Animal animal: animals) {
if (animal instanceof Cat) {
((Cat)animal).meow();
}
if (animal instanceof Dog) {
((Dog)animal).woof();
}
}
}
P.S. The dubious downcasts in the loop body are a perfect example of how lame Java is for disjoint sum (variant) types.
This is related to type erasure. The type is not preserved at runtime. Really, List becomes List of Type Object at runtime. This is why you're getting a compiler warning or should be on animals.add((T) new Cat()); At compile time, Cat does extend animal which is of type T. However, it cannot enforce that a Dog is in the list at that time, therefore the compiler warning.
Generics only work for compile time safety. In your case, how can the compiler know that something bad will happen? It assumes your type definitions, and proceeds off of that. To do more would mean much more elaborate work for the compiler, but there are extended static checkers and other tools that could catch this pre-runtime.
Suffice it to say that there is such a T for which the cast can succeed. As for compiled code, it will be exactly the same as if you wrote animals.add((Animal)new Cat());
Your function doAction is parametrized by a type T that extends the class Animal. So it can be either an object of type Dog or Cat.
You should also note the difference between formal parameter and effective parameter. The formal parameter is the one you use when defining your method, which in your case is List <T> (using it as a shortcut). The effective parameter is the one you "give" to your method when call it, here List<Dog>. .
Lets take a look at animals.add((T) new Cat()) in doAction(). animals is a list which elements are of type T which is either Dog or Cat, so there is no mistake, since that's the type of the formal parameter.
So that's the reason. It is one of the benefits of using parametrize classes.

Useful example with super and obscurity with extends in Generics?

I know that there are a lot of questions about this topic, but unfortunately they couldn't help me to eliminate my obscurities. First of all, look at the following example. I don't understand, why the following "add"-method someCage.add(rat1) doesn't work and aborts with the following exception:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: The method add(capture#2-of ? extends Animal) in the type
Cage is not applicable for the
arguments (Rat)
Is this the same reason why Cage<Rat> is not a Cage<Animal>? If yes, I don't understand it in this example, so I'm not sure what the compiler exactly does. Here is the code example:
package exe;
import cage.Cage;
import animals.Animal;
import animals.Ape;
import animals.Lion;
import animals.Rat;
public class Main {
public static void main(String[] args) {
Lion lion1 = new Lion(true, 4, "Lion King", 8);
Lion lion2 = new Lion(true, 4, "King of Animals", 9);
Ape ape1 = new Ape(true, 2, "Gimpanse", true);
Ape ape2 = new Ape(true, 2, "Orang Utan", true);
Rat rat1 = new Rat(true, 4, "RatBoy", true);
Rat rat2 = new Rat(true, 4, "RatGirl", true);
Rat rat3 = new Rat(true, 4, "RatChild", true);
Cage<Animal> animalCage = new Cage<Animal>();
animalCage.add(rat2);
animalCage.add(lion2);
Cage<Rat> ratCage = new Cage<Rat>();
ratCage.add(rat3);
ratCage.add(rat1);
ratCage.add(rat2);
// ratCage.add(lion1); //Not Possible. A Lion is no rat
Cage<Lion> lionCage = new Cage<Lion>();
lionCage.add(lion2);
lionCage.add(lion1);
Cage<? extends Animal> someCage = new Cage<Animal>(); //? = "unknown type that is a subtype of Animal, possibly Animal itself"
someCage = ratCage; //OK
// someCage = animalCage; //OK
someCage.add(rat1); //Not Possible, but why?
animalCage.showAnimals();
System.out.println("\nRatCage........");
ratCage.showAnimals();
System.out.println("\nLionCage........");
lionCage.showAnimals();
System.out.println("\nSomeCage........");
someCage.showAnimals();
}
}
This is the cage class:
package cage;
import java.util.HashSet;
import java.util.Set;
import animals.Animal;
public class Cage<T extends Animal> { //A cage for some types of animals
private Set<T> cage = new HashSet<T>();
public void add(T animal) {
cage.add(animal);
}
public void showAnimals() {
for (T animal : cage) {
System.out.println(animal.getName());
}
}
}
Moreover, I would be pleased if you could give me a meaningful "super" example with this animal-cage-code. Until now I haven't understood how to use it. There are a lot of theoretical examples and I read about the PECS concept but anyhow I wasn't able to employ it in a meaningful matter yet. What would it mean to have a "consumer" (with super) in this example?
Example of super bound
The introduced transferTo() method accepts Cage<? super T> - a Cage that holds a superclass of T. Because T is an instanceof its superclass, it's OK to put a T in a Cage<? super T>.
public static class Cage<T extends Animal> {
private Set<T> pen = new HashSet<T>();
public void add(T animal) {
pen.add(animal);
}
/* It's OK to put subclasses into a cage of super class */
public void transferTo(Cage<? super T> cage) {
cage.pen.addAll(this.pen);
}
public void showAnimals() {
System.out.println(pen);
}
}
Now let's see <? super T> in action:
public static class Animal {
public String toString() {
return getClass().getSimpleName();
}
}
public static class Rat extends Animal {}
public static class Lion extends Animal {}
public static class Cage<T extends Animal> { /* above */ }
public static void main(String[] args) {
Cage<Animal> animals = new Cage<Animal>();
Cage<Lion> lions = new Cage<Lion>();
animals.add(new Rat()); // OK to put a Rat into a Cage<Animal>
lions.add(new Lion());
lions.transferTo(animals); // invoke the super generic method
animals.showAnimals();
}
Output:
[Rat, Lion]
Another important concept is that while it is true that:
Lion instanceof Animal // true
it is not true that
Cage<Lion> instanceof Cage<Animal> // false
It this were not the case, this code would compile:
Cage<Animal> animals;
Cage<Lion> lions;
animals = lions; // This assignment is not allowed
animals.add(rat); // If this executed, we'd have a Rat in a Cage<Lion>
You can add a Rat to a Cage<Rat> (of course).
You can add a Rat to a Cage<Animal>, because a Rat "is" an Animal (extends Animal).
You cannot add a Rat to a Cage<? extends Animal>, because <? extends Animal> might be <Lion>, which a Rat is not.
In other words:
Cage<? extends Animal> cageA = new Cage<Lion>(); //perfectly correct, but:
cageA.add(new Rat()); // is not, the cage is not guaranteed to be an Animal or Rat cage.
// It might as well be a lion cage (as it is).
// This is the same example as in Kaj's answer, but the reason is not
// that a concrete Cage<Lion> is assigned. This is something, the
// compiler might not know at compile time. It is just that
// <? extends Animal> cannot guarantee that it is a Cage<Rat> and
// NOT a Cage<Lion>
//You cannot:
Cage<Animal> cageB = new Cage<Rat>(); //because a "rat cage" is not an "animal cage".
//This is where java generics depart from reality.
//But you can:
Cage<Animal> cageC = new Cage<Animal>();
cageC.add(new Rat()); // Because a Rat is an animal.
Imagine having your Cage<? extends Animal> created by an abstract factory method, which gets implemented by a subclass. In your abstract base class you cannot tell which type actually gets assigned, neither can the compiler, because maybe the concrete class gets only loaded at runtime.
That means, the compiler cannot rely on Cage<? extends Animal> to not be a Cage of some other concrete subtype, which would make the assignment of a different subtype an error.
Both answers so far have been great. I'd just like to add a tidbit to help your understanding of them.
To further Ron's answer, you may be thinking the following:
"why is it that that someCage.add(rat1) becomes a Cage<? extends Animal>.add(rat1)? Can't someCage point to any Cage of any type which extends Animal (and I've now set it to point to a cage of rats?)"
Totally legitimate question. Thing is, when you do the someCage = ratCage, an element-by-element copy is done from ratCage into someCage. So in fact, you have not simply set someCage to now point to a ratCage. In actuality, someCage is still a Cage<? extends Animal>. You can't do someCage.add(rat1) because you don't know the type of the Cage, only that it's type is bounded above by Animal.
P.S.: You can't add anything to someCage since its type is unknown
I think your question can be answered by the following snippet of code:
Cage<? extends Animal> cage = new Cage<Lion>();
cage.add(rat1);
You can clearly see that the code above shouldn't be valid, since you know that cage currently is a lion cage, and you shouldn't be allowed to add a rat to a lion cage.
The compiler does not what value you have assigned to the cage, so it can't allow cage.add(rat1) even if you assign a rat cage to the cage.

Categories