Understanding wildcard-constraint <? super T> - java

I can work with basic generic expression but the wildcard-constraints just mess with my mind.
Info: Student extends Person and Person extends Animal
List<? super Animal> aList= new ArrayList<>();
// does not compile as expected,
// since the list is restricted to something that has Animal as superclass.
// aList.add(new Object());
aList.add(new Animal()); // I can add animal
aList.add(new Person()); // I can add Person
aList.add(new Student()); // I can add Student
Animal a = new Animal();
Animal b = new Animal();
Person p = new Person();
Student s = new Student();
// test
a = b; //I can assign an animal to another animal
a = p; // I can assign a person to an animal
a = s; // I can assign a student to an animal
Animal animal = aList.get(0); // DOES NOT COMPILE, WHY ?
QUESTION: I don't understand why the last assignment does not work. The examples above show, that anything in that list is definitely an animal, yet I can't get an animal from that list.
MORE SPECIFIC: When I know that I can add only types which have Animal as superclass, why can't I expect to remove objects from type Animal ?
FACT: I can ONLY add objects which extend Animal! I just tried to add a car object and it does not work !
I am starting to doubt my sanity, I hope you can help me. Thank You
Additionally:
Object animal = aList.get(0); // works
Why does this statement work even though I know that I can't add an Object-Type ?
SOLUTION: (Based on the accepted answer)
I misunderstood the meaning of <? super Animal>
What I thought it means: Any class which has Animal as superclass.
What it (apparently) means: Any Class which is superclass of Animal.
Therefore a List might also contain objects of type Object which is why Animal animal = aList.get(0); fails.
Cheers

The other answers here are right, but not stated clearly enough, which is where the confusion is coming from.
A List<? extends Animal> does not mean "A list of things that all extend Animal." It means "A list of some type T, which I won't tell you what it is, but I know that T extends Animal." (In type theory, these are called existential types -- there exists a type T for which our List is a List<T>, but we don't necessarily know what T is.)
The difference is important. If you have "a list of things that all extend Animal", then it would be safe to add a Dog to the list -- but this is not what wildcards express. A List<? extends Animal> means "List of something, where that something extends Animal". It might be a List<Animal>, or a List<Dog>, or a List<Cat> -- we don't know. So we have no reason to think that its safe to add a Dog to that list -- because maybe my List is a List<Cat>.
In your example, you have a List<? super Animal>. This means, a list of some type T, where T is one of the supertypes of Animal. It might be a List<Object>, or a List<Animal>, or if Animal has a supertype HasLegs, it might be a List<HasLegs>. Here, it's safe to put a Dog into this list -- because whatever its a List of, Dog is definitely one of those (Animal, Object, etc), but when you take something out of the list, you have no idea whether its a Dog, an Animal, or just an Object.

List<? super Animal> aList is reference which can be used to handle List<Animal> , it can also be any superclass of Animal such as List<Object>.
In other words List<? super Animal> aList
- is not reference to some list which can store any supertype of Animal.
+ it is reference to list of some specific type which is supertype of Animal (including Animal itself) but you don't know which type it is exactly.
So it could be
List<Object> someList = new ArrayList<>();
someList.add(new Car());//OK since Car is a Object
List<? super Animal> aList = someList;// OK since Object is supertype of Animal
Because of that, code
Animal a = aList.get(0);//and where did that Car come from?
is not safe. Only safe type to store the result of get(0) is Object so you either need
Object o = aList.get(0);
or if you want to make sure that get will return Animal, change the type of your aList reference to List<Animal> or even List<? extends Animal>.

List<? super Animal> means a list of any superclass of Animal. If Animal is a subclass of LivingThing, then List<? super Animal> can be a list of Animals, a list of LivingThings, or a list of Object. In the last two cases, the assignment Animal x = aList.get(0) would of course be illegal, because you cannot assign a LivingThing to a reference of type Animal.
Consider the following method (it will not compile):
void f(List<? super Animal> list) {
Animal a = list.get(0); // line 1
list.add(new Object()); // line 2
}
The method call
List<Object> list = new ArrayList<>();
list.add(new Object());
f(list);
is correct, because Object is a superclass of Animal. However, if the method f would compile, you would try to assign in Line 1 an Object to an Animal reference, so it would not be type safe.
On the other, hand consider the method call:
f(new List<Animal>());
If the method f would compile, we would now be adding an Object instance to a list which should only contain Animals.
That's why both Line 1 and Line 2 are not allowed. If you have a class
public class A<T> {
public put(T in) { }
public T get() { }
}
then for the type A<? super Animal> the method get will return a Object (not an Animal), while the method put expects a parameter of type Animal.

Related

How to specify a java.util.Function that returns another generic type with type covariance?

Suppose I would like to write a method that takes a list and a Function returning another generic type, say Optional. A concrete example for such a method would be one that applies the function to all elements in the list, and returns a list of all elements that didn't result in an empty Optional.
To the best of my understanding, here is how I would write out this method:
public <I, O> List<O> transform(List<I> list, Function<? super I, Optional<? extends O>> function) {
List<O> result = new ArrayList<>();
for (I element : list) {
Optional<? extends O> optional = function.apply(element);
if (optional.isPresent()) {
result.add(optional.get());
}
}
return result;
}
The reason I used wildcard arguments for Function are as follows:
I don't really care if the input to the Function is exactly I. It should be fine to pass anything that takes a parent type of I.
The Optional that the Function returns doesn't have to be exactly O. It should be fine to return an Optional of a subtype of O.
Let's test this by first defining two simple types:
public class Animal {}
public class Cat extends Animal {}
Now suppose we're starting with a list of Cats:
List<Cat> catList = new ArrayList<>();
According to the two points I made about transform taking wildcard arguments above, I would like to transform this list into another list of Animals using the following method:
public Optional<Cat> animalToCat(Animal cat) {
return Optional.empty();
}
This indeed works when I pass a method reference to animalToCat:
List<Animal> animalList = transform(catList, this::animalToCat); // works!
However, what if I don't directly have this method reference available, and would like to store the method in a variable first before passing it to transform later?
Function<Animal, Optional<Cat>> function2 = this::animalToCat;
List<Animal> animalList2 = transform(catList, function2); // does not compile!
Why does the line resulting in animalList compile, but the one resulting in animalList2 doesn't? Through trial and error, I figured out that I can indeed make this compile by changing the type of the variable I'm assigning my method reference to to any of the following:
Function<Animal, Optional<? extends Animal>> function3 = this::animalToCat;
List<Animal> animalList3 = transform(catList, function3); // works
Function<Cat, Optional<? extends Animal>> function4 = this::animalToCat;
List<Animal> animalList4 = transform(catList, function4); // works
Function<? super Cat, Optional<? extends Animal>> function5 = this::animalToCat;
List<Animal> animalList5 = transform(catList, function5); // works
So it seems to be okay to assign the animalToCat method reference, which is clearly one taking an Animal and returning a Optional<Cat>, to other Function types. However, taking the existing animalToCatFunction2 and assigning it to the other types also fails:
animalToCatFunction3 = animalToCatFunction2; // does not compile!
animalToCatFunction4 = animalToCatFunction2; // does not compile!
animalToCatFunction5 = animalToCatFunction2; // does not compile!
I'm very confused as to why it would be okay to treat the this::animalToCat method reference in a way that would make it seem like the returned Optional<Cat> is a covariant type, but that behavior suddenly breaks as soon as the reference is assigned to a variable with a specific type. Is my definition of transform wrong?
See STU's reply for the underlying reason.
To get your example to work, you need to help the Java type system a bit by using more type parameters:
<A, B, C extends B, D extends A> List<B> transform(List<D> list, Function<A, Optional<C>> function) {
List<B> result = new ArrayList<>();
for (D element : list) {
Optional<C> optional = function.apply(element);
if (optional.isPresent()) {
result.add(optional.get());
}
}
return result;
}
Since the dynamic sub-type of the incoming list can be different to the outgoing one, it's useful to add another sub-type to the example:
class Dog extends Animal {}
Then the example code is:
List<Dog> dogList = new ArrayList<>();
List<Animal> animalList = transform(dogList, this::animalToCat);
Function<Animal, Optional<Cat>> function2 = this::animalToCat;
List<Animal> animalList2 = transform(dogList, function2);
EDIT: Modified the type constraints a bit to make it work with the example in the comment as well:
Optional<Animal> catToAnimal(Cat cat) {
return Optional.empty();
}
Function<Cat, Optional<Animal>> function2b = this::catToAnimal;
List<Animal> animalList2b = transform(catList, function2b);
I believe the reason this does not compile:
Function<Animal, Optional<Cat>> function2 = this::animalToCat;
List<Animal> animalList2 = transform(catList, function2);
whereas this does:
List<Animal> animalList = transform(catList, this::animalToCat);
is that bare method references have a type that is not representable in the user-visible type system.
You can think of this::animalToCat as having the "magic" type Function<contravariant Animal, covariant Optional<Cat>>, but as soon as you convert to the user-defined type Function<Animal, Optional<Cat>> you lose the information about the variance of raw functions themselves.
At that point, you can't assign a Function<Animal, Optional<Cat>> to a Function<Animal, Optional<? extends Animal>> for the same reason you can't assign a Function<Optional<Cat>, Animal>to a Function<Optional<? extends Animal>, Animal>.
C.f. Function1[-T1, +R] in Scala.

Java list generics with multiple bounds

I'm struggling to understand why the following code doesn't work :
public <E extends Animal & IQuadruped> void testFunction()
{
List<E> list = new ArrayList<E>();
Dog var = new Dog();
list.add(var);
}
with Dog being the following :
public class Dog extends Animal implements IQuadruped
{
}
And I get a compile error on the add :
The method add(E) in the type List<E> is not applicable for the arguments (Dog)
I just want to make sure my list elements extend/implement both classes, and Dog fullfil those conditions, why is it not working ?
Thank you
What <E extends Animal & IQuadruped> means is "a particular type that is a subtype of both Animal and IQuadruped", and not "any type that is a subtype of both Animal and IQuadruped"
The reason it's difficult to grasp the difference is that in everyday thinking we don't make that distinction explicit. If for example you agree to go out for lunch with someone in a restaurant, and they say "any day next week is good for me", you automatically know that means you need to turn up on the same day. And not that you can go at any time and they'll be there.
In this case there's no guarantee that the E the caller chooses will definitely be Dog, so your code won't work.
The obvious wrong solution is to specify<E extends Dog>, because it would guarantee that E is a subtype of Dog. However this is wrong for the exact same reason, E could be any subtype of Dog, let's say E is a Poodle, so when you create a List<Poodle>, you won't be able to put your new Dog() in there, because it isn't a Poodle.
The correct bound is <E super Dog>, because that means E is definitely a type that you can cast a Dog instance to. It could be Dog itself, it could be Animal or IQuadruped or even Object. But it guarantees that you can put a Dog in the list.
The name of this principle is PECS: producer extends, consumer super, and you can read about it here.
Generics type erasure is what you are getting. By the time the JVM executes the line where you are adding to the list, the generics is already lost. To get this to work, you would have to do something like:
public <E extends Animal & IQuadruped> void testFunction(E param) {
List<E> list = new ArrayList<E>();
list.add(param);
}
public void addDog() {
testFunction(new Dog())
}

Java. Wildcards in Collections

Java. Wildcards in Collections
I’m having a lot of trouble understanding wildcards in Collections, even after reading similar posts in Stack Overflow and various tutorials sites. I've made a very simple example below. Can you explain how I would choose between Collection< myClass >, Collection< ? Extends MyClass >, and Collection< ? Super MyClass >?
package z5;
import java.util.ArrayList;
public class Z5 {
public static class Animal{
}
public static class Mammal extends Animal{
}
public static class Reptile extends Animal{
}
public static class Lion extends Mammal{
}
public static class Tiger extends Mammal{
}
public static class Snake extends Reptile{
}
public static void main(String[] args) {
ArrayList<Mammal> catHouse1 = new ArrayList<Mammal>();
catHouse1.add(new Lion());
catHouse1.add(new Tiger());
catHouse1.add(new Mammal());
catHouse1.add(new Animal()); //ERROR
ArrayList<? super Mammal> catHouse2 = new ArrayList<Mammal>();
catHouse2.add(new Lion());
catHouse2.add(new Tiger());
catHouse2.add(new Mammal());
catHouse2.add(new Animal()); //ERROR
ArrayList<? extends Mammal> catHouse3 = new ArrayList<Mammal>();
catHouse3.add(new Lion()); //ERROR
catHouse3.add(new Tiger()); //ERROR
catHouse3.add(new Mammal()); //ERROR
catHouse3.add(new Animal()); //ERROR
ArrayList<Mammal> zooMammals = new ArrayList<Mammal>();
zooMammals.addAll(catHouse1);
zooMammals.addAll(catHouse2); //ERROR
zooMammals.addAll(catHouse3);
ArrayList<Animal> zooAnimals = new ArrayList<Animal>();
zooAnimals.addAll(catHouse1);
zooAnimals.addAll(catHouse2); //ERROR
zooAnimals.addAll(catHouse3);
}
}
In the example above, I make a hierarchy of classes. Animal is the superclass of Mammal and Reptile, and Mammal is the superclass of Lion and Tiger.
I make ArrayLists for three Cat Houses in my zoo. The first is simply ArrayList< Mammal >. I can add any Object of type Mammal or its subclasses.
The second is ArrayList< ? super Mammal>. I can also add any Object of type Mammal or its subclasses.
The third is ArrayList< ? extends Mammal>. I can't add anything to it.
Finally, I add my three cat houses into zoo Collections. Animal and Mammal are the main superclasses here, and the behavior is the same regardless of which type the recipient ArrayList holds.
ArrayList < Mammal > and ArrayList can be added to the zoos.
ArrayList cannot.
Here are my questions:
1) If I want to make an array that holds all subclasses of a certain superclass, why would I need a wildcard? Couldn't I just declare everything ArrayList< Superclass > and get the functionality I need?
2) I understand that "< ? extends superclass >" accepts the superclass and all its subclasses. Ergo, < ? extends Mammal >" accepts Mammals, Lions, and Tigers. That sounds exactly like "< Mammal >". What's the difference?
3) I read that "< ? super className >" accepts any class that's a superclass of className. That doesn't sound right. In the example above, Lions are not superclasses of Mammals, but "< ? super Mammal >" accepts Lions. Animals are superclasses of Mammals, but "< ? super Mammal >" doesn't accept it. I think I have wrong information there.
4) If "< ? extends superclass >" is read-only, how dod I populate it to begin with? And what's the point of having an empty list that you can only read from?
5) Why does the addAll method not work on "< ? super className >"?
I know these are fundamental questions, and I understand they've been answered before. I'm trying to give a code example that's as simple as possible and hopefully get me an answer that's as clear as possible. Thanks in advance for any advice you can offer.
I won't go into great details.
List<Animal> means: this list contains instances of Animal. So you can add any Animal you want, and you're sure to get an Animal when getting elements from this list.
List<? extends Animal> means: this list is a generic list, but we don't know the type of the generic type. All we know about it is that the generic type is Animal, or any subclass of Animal. So it could be a List<Animal>, a List<Reptile> or a List<Lion>, for example. But we don't know. So, when getting an element from this list, you're guaranteed to get an Animal. But you won't be allowed to add anything into the list, because you don't know its type. If you were allowed to add something, you could store a Lion in a List<Reptile>, and the list wouldn't be type-safe anymore.
List<? super Animal> means: this list is a generic list, but we don't know the type of the generic type. All we know about it is that the generic type is Animal, or any superclass or super interface of Animal. So it could be a List<Animal> or a List<Object>, for example. So, when getting an element from this list, all you can say for sure is that it's an Object. What you can do for sure is to add any Animal you want in this list though, because both List<Animal> and List<Object> accept Animal, Lion, Reptile or whatever subclass of Animal.
Most of the time, you use these wildcards for arguments of your methods.
When a method takes a list as argument and is only interested in reading from the list (i.e. the list is a producer), you'll use List<? extends Animal>. This makes your method more reusable, because it can be used with a List<Animal>, but also with a List<Reptile>, a List<Lion>, etc.
When a method takes a list as argument and is only interested in adding elements to the list (i.e. the list is a consumer), you'll use List<? super Animal>. This makes your method more reusable, because it can be used with a List<Animal>, but also with a List<Object>.
This rule is known as PECS: Procucer: Extends; Consumer: Super.
If your method takes a list as argument and must both get and add elements to/from the list, you'll use a List<Animal>.
If you just want a list that can contain Animal or subclasses Animal you should use List<Animal>. I think this is what you need most of the time.
extends:
ArrayList<? extends Mammal> list = ..
This means that list is of type Mammal or one of its sub classes. So you can do this:
ArrayList<? extends Mammal> list = new ArrayList<Tiger>(); // List of type Tiger
When using <? extends Mammal> you can't insert anything into list (except null). The reason that there is no typesafe way to insert anything. You can't add a Mammal to list because list might be of type Tiger (like in the example above). A Mammal is no Tiger so this can't work.
You can't add a Tiger to list either. That's because <? extends Mammal> doesn't tell you anything about Tiger. It would be also possible that list is of type Lion.
super:
With <? super Mammal> it is the opposite situation. <? super Mammal> means that the list is of type Mammal or one of its superclasses. You can do this:
ArrayList<? super Mammal> list = new ArrayList<Animal>(); // List of type Animal
You can add any subclass of Mammal to this list. This is safe because subclasses of Mammal are always subclasses of Animal. However you can't get anything out of the list with another type than Object. Thats because you don't know the exact list type.
Mammal m = list.get(0); // can't work because list can be a List<Animal>

Add Strings through use of generic 'extends' causes compiler error

Below code :
List<? extends String> genericNames = new ArrayList<String>();
genericNames.add("John");
Gives compiler error :
Multiple markers at this line
- The method add(capture#1-of ? extends String) in the type List is not applicable for the
arguments (String)
- The method add(capture#1-of ?) in the type List is not applicable for the arguments (String)
What is causing this error ? Should I not be able to add Strings or its subtype since I am extending String within the type parameter ?
When you use wildcards with extends, you can't add anything in the collection except null. Also, String is a final class; nothing can extend String.
Reason: If it were allowed, you could just be adding the wrong type into the collection.
Example:
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
Now you have List<? extends Animal>
public static void someMethod(List<? extends Animal> list){
list.add(new Dog()); //not valid
}
and you invoke the method like this:
List<Cat> catList = new ArrayList<Cat>();
someMethod(catList);
If it were allowed to add in the collection when using wildcards with extends, you just added a Dog into a collection which accepts only Cat or subtype type. Thus you can't add anything into the collection which uses wildcards with upper bounds.
String is a final class and cannot be extended. Additionally, for the case you seem to be interested in, you do not need the extends keyword. List<String> will do what you seem to want. That will allow Strings and sub-classes of String (if such a thing could exist, which it can't since String is final).
Just want to add to the answer of GanGnaMStYleOverFlow that you can add an object of any subtype of Animal to the following list:
List<Animal> animals = new ArrayList<Animal>();
You should use such list whenever you think that it can contain any kind of animals.
On the other hand, you should use List<? extends Animal> when you want to specify that the list contains some kind of animal but you don't know which one. Since you don't know what kind of animals are there, you cannot add any.

Generic lower unbound vs upper bounded wildcards

import java.util.List;
import java.util.ArrayList;
interface Canine {}
class Dog implements Canine {}
public class Collie extends Dog {
public static void main(String[] args){
List<Dog> d = new ArrayList<Dog>();
List<Collie> c = new ArrayList<Collie>();
d.add(new Collie());
c.add(new Collie());
do1(d); do1(c);
do2(d); do2(c);
}
static void do1(List<? extends Dog> d2){
d2.add(new Collie());
System.out.print(d2.size());
}
static void do2(List<? super Collie> c2){
c2.add(new Collie());
System.out.print(c2.size());
}
}
The answer for this question tell that when a method takes a wildcard generic typ, the collection can be accessed or modified, but not both. (Kathy and Bert)
What does it mean 'when a method takes a wildcard generic typ, the collection can be accessed or modified, but not both' ?
As far as I know,
The method do1 has List<? extends Dog> d2 so d2 only can be accessed but not modified.
The method d2 has List<? super Collie> c2 so c2 can be accessed and modified and there is no compilation error.
Generic guidelines
You cannot add a Cat to a List<? extends Animal> because you don't know what kind of list that is. That could be a List<Dog> also. So you don't want to throw your Cat into a Black Hole. That is why modification of List declared that way is not allowed.
Similarly when you fetch something out of a List<? super Animal>, you don't know what you will get out of it. You can even get an Object, or an Animal. But, you can add an Animal safely in this List.
I pasted your code into my IDE. The following error was signalled inside do1:
The method add(capture#1-of ? extends Dog) in the type List is not applicable for the arguments (Collie)
This is, of course, as expected.
You simply cannot add a Collie to a List<? extends Dog> because this reference may hold for example a List<Spaniel>.
The answer for this question tell that when a method takes a wildcard generic typ, the collection can be accessed or modified, but not both. (Kathy and Bert)
That's a fair first approximation, but not quite correct. More correct would be:
You can only add null to a Collection<? extends Dog> because its add method takes an argument of ? extends Dog. Whenever you invoke a method, you must pass parameters that are of a subtype of the declared parameter type; but for the parameter type ? extends Dog, the compiler can only be sure that the argument is of compatible type if the expression is null. However, you can of course modify the collection by calling clear() or remove(Object).
On the other hand, if you read from a Collection<? super Dog>, its iterator has return type ? super Dog. That is, it will return objects that are a subtype of some unknown supertype of Dog. But differently, the Collection could be a Collection<Object> containing only instances of String. Therefore
for (Dog d : collection) { ... } // does not compile
so the only thing we know is that instances of Object are returned, i.e. the only type-correct way of iterating such a Collection is
for (Object o : collection) { ... }
but it is possible to read from a collection, you just don't know what types of objects you will get.
We can easily generalize that observation to: Given
class G<T> { ... }
and
G<? extends Something> g;
we can only pass null to method parameters with declared type T, but we can invoke methods with return type T, and assign the result a variable of type Something.
On the other hand, for
G<? super Something> g;
we can pass any expression of type Something to method parameters with declared type T, and we can invoke methods with return type T, but only assign the result to a variable of type Object.
To summarize, the restrictions on the use of wildcard types only depend on the form of the method declarations, not on what the methods do.
I pasted your code into IDEONE http://ideone.com/msMcQ. It did not compile for me - which is what I expected. Are you sure you did not have any compilation errors?

Categories