I have a List<? extends MyClass> list and I want to add into this list objects whose class extends MyClass and objects which are instances of MyClass:
list.add(new ClassThatExtendsMyClass());
list.add(new MyClass());
but eclipse shows the build error:
The method add(capture#9-of ? extends MyClass) in the
type List is not
applicable for the arguments (MyClass)
How can I get around this?
Java keyword extends in generic type of reference is used to restrict actual generic type realization to be no less derived than the named type. Especially it can be a subclass. One should use it in case type is used to extract values and operate on them. You then use the interface of the base class not concerning the actual type (realization/implementation) of that class.
When you've got a specific class and need to pass (put) into collection, or other generic class object, the reference to point at that object should have super keyword, which restricts the actual object to be no more derived than the named type.
Code example below. Assume we have classes Base and Derived, where Derived extends Base, class Base have an interface method foo() and both have default constructor.
void service() {
List<Base> theList = new ArrayList<Base>();
produceObjects(theList);
consumeObjects(theList);
}
void produceObjects(List<? super Base> consumerList) {
consumerList.add(new Derived());
}
void consumeObjects(List<? extends Base> producerList) {
for (Base base : producerList) {
base.foo();
}
}
You can declare your reference as List<MyClass>.
You'll be able to add anything extending MyClass, including instances of MyClass.
This is not possible. List<? extends MyClass> list could actually point to a ArrayList<ClassThatExtendsMyClass>. Which can't hold instances of some other subclass of MyClass.
List<? extends Number> numbers = new ArrayList<Integer>();
numbers.add(Long.valueOf(2)); // not possible since 'Integer' array can't hold Longs
If you want to add things you should declare your variable 'list' as List<? super MyClass>. This will enable you to add any subclass of 'MyClass' into the list.
List<? super Number> numbers = new ArrayList<Number>();
numbers.add(Long.valueOf(2));
This is known as the 'get' and 'put' principle. If you want to 'get' stuff you need to have the List<? extends MyClass> syntax whilst if you want to 'put' stuff you need to have the List<? super MyClass> syntax. Ofcourse if you need to do both then you need to use List<MyClass> syntax.
Try this:
List<MyClass>
It should work
Define it this way:
List<MyClass> list
Related
The basic thing I want to achieve is to map a list of references List<Ref<Thing>> to a list of the actual objects, but given by the superclass List<SuperThing>. In this example, Thing extends SuperThing and Ref<Thing> has a method public Thing get() to get the referenced object.
The method that I assumed valid:
public <T> List<T> refsToObjects(List<Ref<? extends T>> list) {
List<T> result = new ArrayList<T>();
for(Ref<? extends T> ref : list) {
result.add(ref.get());
}
return result;
}
But when I try to use it
List<Ref<Thing>> refs;
List<SuperThing> objectList = refsToObjects(refs);
I get this error message: The method refsToObjects(List<Ref<? extends T>>) is not applicable for the arguments (List<Ref<Thing>>)
I did not actively use the ? extends T wildcard structure before, but what am I doing wrong?
It works, if you specify the "extended" parameter also as generic parameter:
public <T, S extends T> List<T> refsToObjects(List<Ref<S>> list) {
List<T> result = new ArrayList<T>();
for(Ref<S> ref : list) {
result.add(ref.get());
}
return result;
}
Declare your method as taking List<? extends Ref<? extends T>> instead:
public <T> List<T> refsToObjects(List<? extends Ref<? extends T>> list) { ... }
Nothing should have to change within the body.
EDIT: type inference still seems to fail at the call site using this solution. It only works with a call like this.<SuperThing>refsToObjects(refs). So wrm's solution using an additional type parameter is preferable if you can expect this kind of usage.
As I can see it, there are two errors in your code. The first is to believe that the type List<Ref<? extends Thing>> is a supertype for List<Ref<Thing>>. If we create a subclass of Thing like DerivedThing, we cannot add an instance of Ref<DerivedThing> to a list of List<Ref<Thing>>:
List<Ref<Thing>> refs = new ArrayList<Ref<Thing>>();
refs.add(new Ref<Thing>()); // OK.
refs.add(new Ref<DerivedThing>()); // Error!
However, if we replace this with List<Ref<? extends Thing>> then there is no more problem with the class DerivedThing:
List<Ref<? extends Thing>> refs = new ArrayList<Ref<? extends Thing>>();
refs.add(new Ref<Thing>()); // Still OK.
refs.add(new Ref<DerivedThing>()); // Now OK!
Therefore, if the compilator was to allow to pass of a value of List<Ref<? extends Thing>> to a function taking List<Ref<? extends Thing>> as its argument, this would allow the function to add some invalid item to the list.
The second error is to think that the base type (or erasure type) of <? extends Thing> is SuperThing instead of remaining Thing. Here, <? extends Thing> designates the collection of type composed of Thing and its derived classes and not the collection of SuperThing and its derived classes. Therefore, we could write:
List<Ref<? extends Thing>> refs = new ArrayList<Ref<? extends Thing>>();
refs.add(new Ref<Thing>());
List<Thing> objectList = refsToObjects(refs);
or, with SuperThing as the erasure type:
List<Ref<? extends SuperThing>> refs = new ArrayList<Ref<? extends SuperThing>>();
refs.add(new Ref<Thing>());
List<SuperThing> objectList = refsToObjects(refs);
but not a combination of both because List<SuperThing> is not a superclass for List<Thing>. Notice that we can stil add a Ref<Thing> to a List<Ref<? extends SuperThing>>. Therefore, use of one of the above solution or use the wrm's solution if you want to keep List<Ref<Thing>> as your starting point.
Personally, I would prefer to use polymorphism at its fullest extend and always reference everything from a SuperThing; even when creating Thing or Ref<Thing> objects. For example, if we add a parameter of type T to the constructor of Ref():
List<Ref<SuperThing>> refs = new ArrayList<Ref<SuperThing>>();
refs.add(new Ref<SuperThing>(new Thing()));
List<SuperThing> objectList = refsToObjects(refs);
Note that we are now passing an object of type Thing to a reference of type SuperThing in the constructor of Ref(). By using the superclass of the hierarchy as the reference for all the derived objects, all the coding become much more simpler. OOP works very well and very easily when you choose to see all the objects mostly only through their superclass and this extends to the use of generic.
The types must match exactly, so:
List<Ref<? extends Thing>> refs = new ArrayList<Ref<? extends Thing>>();
List<SuperThing> objectList = refsToObjects(refs);
should work.
It will also work if you do something like this:
List<Ref<Thing>> refs;
List<SuperThing> objectList = this.<Thing>refsToObjects(refs);
What is happening is that the method expects something which extends T. but you never define T. The one explained by #wrm defines it in the method.
I have a group of classes that all implement a validation interface which has the method isValid(). I want to put a group of objects--all of different classes--into an ArrayList, loop through them and call isValid() on each.
Here's my code
Email email = new email();
Address address = new Address();
ArrayList<? extends Validation> myValidationObjects = new ArrayList();
But when I try to do:
myValidationObjects.add(email);
I get:
The method add(capture#2-of ? extends Validation) in the type ArrayList
is not applicable for the arguments (Email)
Both Email and Address implement Validation.
According to this document, I should be able to use extends for both interfaces and subclasses.
List<? extends Validation> myValidationObjects
Incorrect reading
"myValidationObjects is list of objects that extend Validation."
Correct reading
"myValidationObjects can be a list of any type that extends Validation. For example, it could be a List<RangeValidation> or a List<RegexValidation>."
Since there is no object you can legitimately add to both a List<RangeValidation> and a List<RegexValidation>, Java prevents you to call add on a variable of such type.
Your case is in fact the simpler one: you need the definite type List<Validation>.
You can use:
List<Validation> myValidationObjects = new ArrayList<>(); // Java 7
List<Validation> myValidationObjects = new ArrayList<Validation>(); // pre Java 7
Now you can add any instance of a class that implements Validation to that list.
The declaration ArrayList<? extends Validation> means a list of an unknown class that extends Validation. Email is not compatible with this unknown class.
You can use ArrayList<Validation> for your list.
If a generic class's T is <? extends Foo>, then the only thing you can pass to a method that takes T is null -- not any subclass that extends Foo.
The reason is that List<? extends Validation> doesn't mean "a list of things that extend Validation". You can get that with just List<Validation>. Instead, it means "a list of some type, such that that type extends Validation."
It's a subtle distinction, but basically the idea is that List<? extends T> is a subtype of List<T>, and you therefore don't want to be able to insert anything into it. Think of this case:
List<FooValidation> foos = new ArrayList<>();
List<? extends Validation> validations = foos; // this is allowed
validations.add(new BarValidation()); // not allowed! this is your question
FooValidation foo = foos.get(0);
If the third line were allowed, then the last line would throw a ClassCastException.
I took a look on questions q1, q2, q3, but they don't cover exactly my question.
Note that ArrayList<A> and ArrayList<? extends A> are to be used for declaring a variable or a parameter (not for creating a new generic class).
Are both expressions equivalent when declaring an object attribute (case 1)?:
class Foo {
private ArrayList<A> aList; // == ArrayList<? extends A> aList;
}
EDIT: Are both expressions equivalent from the point of view of what
kind of objects are allowed to be added to aList?, but different
in the same sense as the following case?
but they are different when used in a parameter declaration (case 2)?:
void methodFoo(ArrayList<A> al) != void methodFoo(ArrayList<? extends A> al)
because the first one only allows to be passed ArrayList objects
while the second would be like "more permissive" allowing to be sent
ArrayList<A1> and ArrayList<A2> (as long as A1 and A2 extends A)?
If this is right, is there any other scenario where the two expressions are
effectively different?
Thanks,
Let's have a look at some practical examples. Say, you have:
List<Number> list;
This means that whatever is assigned to this variable or field takes Number and outputs Number, so you always know what to expect. Integer can be added to this list since Integer extends Number. However, you can't assign, say, ArrayList<Long> to this list.
But consider this case:
List<? extends Number> list;
This one says: hey, that's a list of something that extends Number, but no one knows what exacty. What does this mean? This means that you can assign, for example, ArrayList<Long> to this list, which you couldn't in the first case. You still know that whatever this list outputs will be a Number, but you can't put an Integer in it anymore.
There is also an opposite case:
List<? super Number> list;
By printing that you say: that's a list of Number or its superclasses. This is where everything becomes vice-versa. The list can now refer to ArrayList<Object> and ArrayList<Number>. Now we don't know what this list will output. Will it be a Number? Will it be an Object? But now we know that we could put a Number in this list as well as any subclass of Number like Integer or Long.
There is a rule, by the way, which says producer extends, consumer super (PECS for short). If you need the list to output the values, it is a producer, this is the second case. If you need the list to accept values, it is a consumer, this is the third case. If you need both, don't use wildcards (that's the first case).
I hope this clears up matters.
This will explain the difference:
public class GenericsTest {
private ArrayList<A> la;
private ArrayList<? extends A> lexta;
void doListA(ArrayList<A> la) {}
void doListExtA(ArrayList<? extends A> lexta) {}
void tester() {
la = new ArrayList<SubA>(); // Compiler error: Type mismatch
doListA(new ArrayList<SubA>()); // Compiler error: Type mismatch
lexta = new ArrayList<SubA>();
doListExtA(new ArrayList<SubA>());
}
static class A {}
static class SubA extends A {}
}
As you see, calling a method and assigning a variable/instance field have the same rules. Look at the method call as an assignment of your argument to its declared parameter.
ArrayList<A> means a specific class A, where as ArrayList<? extends A> means class A or any class which extands A (Sub class of A) this make it more generic
Using private ArrayList<A> aList; as a variable declaration is not really equivalent to using the wildcard private ArrayList<? extends A> aList;
The wildcarded version will allow you to assign any ArrayLists of types that extend A and A itself but will refuse to add elements to the list as it cannot decide if it is type safe. With ArrayList<A> on the other hand you can only assign ArrayLists (or extensions of ArrayList) of type A and you can then add A elements and any elements extending A to it.
FYI: you should prefer using a more abstract type for declaring your variables/parameters like List<A> or Collection<A>.
The main difference is that if the generic form is used as an argument or return type in a method in a base class (or interface), it allows a greater range of type signatures to count as overriding instead of overloading.
Function override-overload in Java
For example, the following code is legal (in Java 7):
interface A
{
List<? extends Number> getSomeNumbers();
}
class B implements A
{
#Override
public ArrayList<Integer> getSomeNumbers()
{
return new ArrayList<>();
}
}
Difference between Enumeration<? extends ZipEntry> and Enumeration<ZipEntry>?
All of this means that sometimes you can write come code that requires less casts when someone else is using it. Which should not only reducing the amout of typing they have to do, but also eliminate possible failures.
Of course, the problem with Java generics is that they were introduced in a way that was constrained by backwards compatibility. So not everything works that you might think should, and the details get pretty hairy as to what exactly works and what doesn't.
http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ812
It is hard to grasp at first, but inheritance doesn't apply with generics, ie if B extends A, List<B> is not a "subclass" of (can not be assigned to) List<A>. Further, List<? extends A> is not a "subclass" of (can not be assigned to) List<A>.
I just tried to create a ListDataModel with a bounded type, like this:
DataModel<? extends Foo> model = new ListDataModel<? extends Foo>(fooList);
, where fooList is of the type List<? extends Foo>. I get the following error:
unexpected type
required: class or interface without bounds
found: ? extends Foo
My current workaround is to copy my data into an ArrayList<Foo>, and build a DataModel<Foo> from that, but I would like to know why this is necessary, and if there is any way to make it work?
<? extends Foo> means "some type, I don't know which one, which is or extends Foo". When constructing the data model, you need to tell him which type of data it contains, not just one unknown type.
Just construct your data model like this:
DataModel<? extends Foo> model = new ListDataModel<Foo>(fooList);
Unfortunately, the ListDataModel<Foo> constructor only accepts a List<Foo>, and not a List<? extends Foo>. It seems to me like a misconception. For example the HashSet<E> constructor takes a Collection<? extends E> as argument. If you accept the type safety warning, just casting your list to a List<Foo> should work.
Since ListDataModel is read only, it is wrong for its constructor to accept only List<E>. It's ok to cast to bypass this design flaw.
A more general question: suppose ListDataModel is writable, what now?
If fooList is a List<? extends Foo>, then it certainly is a List<W> for a concrete W which extends Foo. Then we should be able to new ListDataModel<W>(fooList), the result type is a DataModel<W>, which is assignable to DataModel<? extends Foo> model.
This is how compiler internally reason about wildcards (wildcard capture); too bad we can't access W directly in Java (it's a so called non-denotable type), but we can cause wildcard capture through method invocation:
static <W> ListDataModel<W> make(List<W> list)
{
return new ListDataModel<W>(list);
}
List<? extends Foo> fooList = ...;
DataModel<? extends Foo> model = make( fooList );
When compiling make( fooList ), compiler internally refines the type of fooList to a List<W> where <W extends Foo>; then the rest works natually.
In Java 7, type inference is extended to constructors with <> syntax
List<? extends Foo> fooList = ...;
DataModel<? extends Foo> model = new ListDataModel<>(fooList); // OK in Java 7
With <>, constructor call is pretty much the same as method calls; so make() is no longer needed. Prior to Java 7, static factory methods like make() were needed to amend the problem that constructors don't do inference. That practice is now obsolete.
I have the following class:
interface Able{/* ... */}
class A implements Able{/* ... */}
and I have
Map<String,? extends Able> as;
as = new HashMap<String, A>();
why does the following cause an error:
as.put("a", new A());
Any ideas?
The reference to java generics is good (jdk site).
Indeed #Oli_Charlesworth gave a good answer, but maybe this one will be more complete.
In a Collection<? extends Able> you can't insert anything that's right.
If you have
class A implements Able {...}
and
class B implement Able {...}
Then, Collection<? extends Able> is a super type of both :
Collection<A>
Collection<B>
Thus it is legal to write some statement like
//Code snippet 01
Collection< ? extends Able > list;
Collection<A> listA;
Collection<B> listB;
list = listA;
list = listB;
That is indeed the reason why the wildcard notation Collection<? extends Able> exists.
But, here things are getting more interesting :
In a Collection<A> you can only insert objects that are A (including subclasses). Same for Collection<B>. In both you can't add something that is just Able. For instance :
//Code snippet 02
listA.add( new A() ); //valid at compile-time
listA.add( new B() ); //not valid at compile-time
listB.add( new B() ); //valid at compile-time
listB.add( new A() ); //not valid at compile-time
Thus, if you group what we saw in code snippets 01 & 02, you will understand that it's absolutely impossible for the compiler to accept a statement like :
Collection< ? extends Able > list;
list.add( new A() ); //not allowed, will work only if list is List<A>
list.add( new B() ); //not allowed, will work only if list is List<B>
So yes, the super type Collection< ? extends Able > doesn't accept to add anything. More general types offer the intersection of functionalities of subtypes, and, as such, less features that subtype. Here, we lose the ability to add A objects and B objects. Those feature will happen later in the hierarchy... and it even means that we can't add anything in the super class Collection< ? extends Able >
Additional remark :
Also, note that in a Collection<Able> you can add whatever you want like this :
Collection< Able > list;
list.add( new A() ); //valid
list.add( new B() ); //valid
But, Collection<Able> is not a superclass of Collection<A> and Collection<B>. It would mean, as with any inheritance relation, that subclasses can do whatever their superclass can do, as inheritance is specialization. So, this would mean that we could add A objects and B objects to both subclasses Collection<A> and Collection<B> and that is not the case. So as it's not a superclass you can't have :
Collection<Able> list;
Collection<A> listA;
Collection<B> listB;
list = listA; //not valid because there is no inheritance hierarchy
list = listB; //not valid because there is no inheritance hierarchy
Note that inheritance is a hyperonimic relation (generalization/specialization) and collections define a meronimic relation (container/containee). And it's a headache to combine both of them formally, even though it's somewhat used quite easily by the fuzzy creatures humans are, for instance in the french figure of speech : synecdocque. :)
From http://download.oracle.com/javase/tutorial/extra/generics/wildcards.html:
There is, as usual, a price to be paid
for the flexibility of using
wildcards. That price is that it is
now illegal to write into [a wildcard-based container]. For instance,
this is not allowed:
public void addRectangle(List<? extends Shape> shapes) {
shapes.add(0, new Rectangle()); // Compile-time error!
}
You should be able to figure out why
the code above is disallowed. The type
of the second parameter to
shapes.add() is ? extends Shape-- an
unknown subtype of Shape. Since we
don't know what type it is, we don't
know if it is a supertype of
Rectangle; it might or might not be
such a supertype, so it isn't safe to
pass a Rectangle there.
A good way to understand the issue is to read what the wildcard means:
Map<String,? extends Able> as;
"A map with keys of type String and values of one type that extends Able."
The reason why add operations are not allowed is because they "open the door" to introduce different types in the collection, which would conflict with the typing system.
e.g.
class UnAble implements Able;
Map<String,UnAble> unableMap = new HashMap<String,UnAble>();
Map<String,? extends Able> ableMap = unableMap;
ableMap.put("wontwork",new A()); // type mismatch: insert an A-type into an Unable map
A correct use of the the wildcard construction would be:
Result processAble(Map<String,? extends Able>) { ... read records & do something ... }
Map<String,A> ableMap = new HashMap<String,A>;
ableMap.put("willwork",new A());
processAble(as);
processAble(unableMap); // from the definition above
declaration of
Map<String,? extends Able> as;
means "any map, with String keys, and values being subtype of Able". So, for example, you can do following:
Map<String,? extends Able> as = new HashMap<String, SubSubAble>();
And now let's look at this example:
Map<String,? extends Able> as = new HashMap<String, SubSubAble>();
as.put("key", new A() );
If it were correct, you'll finish having HashMap with content {"key", new A()} - which is type-error!
Collection<?> is the supertype for all kinds of collection. It is not a collection that can hold any type. At least that was my misunderstanding of the whole concept.
We can use it where we don't care about the generic type, like in this example:
public static void print(Collection<?> aCollection) {
for (Object o:aCollection) {
System.out.println(o);
}
}
If we had chosen the signature instead:
public static void print(Collection<Object> aCollection)
we would have limited ourselves to collections of type Collection<Object> - in other words, such a method wouldn't accept a Collection<String> type value.
So a Collection<?> type is not a collection that can take any type. It only takes the unknown type. And as we don't know that type (its unknown ;) ), we can never add a value, because no type in java is a subclass of the unknown type.
If we add bounds (like <? extends Able>), the type is still unknown.
You're looking for a declaration of a map, whose values all implement the Able interface. The correct declaration is simply:
Map<String, Able> map;
Let's assume we have two types A and B that subclass Able and two additional maps
Map<String, A> aMap;
Map<String, B> bMap;
and want a, method that returns any map whose values implement the Able interface: then we use the wildcard:
public Map<String, ? extends Able> createAorBMap(boolean flag) {
return flag ? aMap: bMap;
}
(again with the constraint, that we can't add new key/value pairs to the map that is returned by this method).
You can't insert any object of any type in a collection declared using the wild card '?'
you can only insert “null”
Once you declare a collection as List, the compiler can't know that it's safe to add a SubAble.
What if an Collection<SubSubAble> had been assigned to Collection<Able>? That would be a valid assignment, but adding a SubAble would pollute the collection.
How can elements be added to a wildcard generic collection?