I have some code like this
import com.google.common.collect.Sets;
public void handleInput(Set<Object> conditions){
Set<Set<Object>> powerSet = Sets.powerSet(conditions);
...
}
This works fine. But I want to do this:
public void handleInput(Set<? extends Object> conditions){
Set<Set<? extends Object>> powerSet = Sets.powerSet(conditions);
...
}
so I can get the powerset of objects that are subclasses of object. But this won't compile and I get the error:
Type mismatch: cannot convert from Set<Set<capture#1-of
? extends Object>> to Set<Set<? extends Object>>
How can I achieve this goal?
EDIT: I guess it has something to do with the generic type getting erased at compile time, so that the compiler can't know that powerSet won't add something illegal to the sets it's creating. I've reworked the client, by casting all the inputs to Object, and removing the wildcard altogether. Is this the best way? Thanks!
In this case it doesn't make any sense - since all Java classes extend java.lang.Object at some point.
So ? extends Object is redundant.
But speaking of Sets.powerSet, this works like a charm:
public class TestClass {
public static class A {}
public static class B extends A {}
public static class C extends B {}
public Set<? extends Set<? extends A>> exampleMethod(Set<? extends A> input) {
return Sets.powerSet(input);
}
public static void main(String[] args) {
final TestClass testClass = new TestClass();
final A a = new A();
final B b = new B();
final C c = new C();
System.out.println(
testClass.exampleMethod(
ImmutableSet.of(a, b, c)
)
);
}
}
as #slnowak notes, when you are extending Object, the code is really redundant.
However, to understand the Exception and avoid it...
public void handleInput(Set<? extends Object> conditions){
Set<? extends Set<? extends Object>> powerSet = Sets.powerSet(conditions);
...
}
this will compile and, more usefully, you can restrict the types in your conditions argument using this method, for instance - you could have:
public void handleInput(Set<? extends Number> conditions){
Set<? extends Set<? extends Number>> powerSet = Sets.powerSet(conditions);
...
}
and this would prevent you passing in sets that had non-numeric types and warn you of this at compile time.
Related
I have a generic interface defined as:
public interface ItemService<T extends Slicer, E extends ItemSlice> {
E getItemHistory(final String id, final T slicer);
}
And an implementation:
public class DynamoDbItemService implements ItemService<DynamoDbSlicer, DynamoDbItemSlice> {
public DynamoDbItemSlice getItemHistory(final String id, final DynamoDbSlicer slicer) {
}
}
Here are the definitions of the four classes referenced above:
public interface Slicer {
Map<String, ? extends Serializable> pointer();
}
public class DynamoDbSlicer implements Slicer {
public Map<String, AttributeValue> pointer() {
}
}
public interface ItemSlice extends Slice<Item> {
}
public interface Slice<T> {
List<T> data();
Slicer next();
}
public class DynamoDbItemSlice implements ItemSlice {
publi ImmutableList<Item> data() {}
public DynamoDbSlicer next() {}
}
I would like to reference the ItemService interface but for it to be bound to the DynamoDbItemService implementation so I can swap it out if necessary which I can do like so:
ItemService<? extends Slicer, ? extends ItemSlice> itemService = new DynamoDbItemService itemService();
but if I try to use itemService like this:
ItemSlice slice = itemService.getItemHistory(itemId, DynamoDbSlicer.first(1));
slice = itemService.getItemHistory(itemId, slice.next());
I get these two compilation errors:
Error:(231, 82) java: incompatible types: item.pagination.DynamoDbSlicer cannot be converted to capture#1 of ? extends pagination.Slicer
Error:(238, 62) java: incompatible types: pagination.Slicer cannot be converted to capture#2 of ? extends pagination.Slicer
I understand from this question that ? wildcards cannot be identical so my question is - can I do what I want - work with the interface? If so, how? Or am I approaching this incorrectly?
I have asked two previous questions related to this which have helped along the way (first and second)
I don't see a reason why the following wouldn't work for you:
ItemService<DynamoDbSlicer, DynamoDbItemSlice> itemService = new DynamoDbItemService();
ItemSlice slice = itemService.getItemHistory("", new DynamoDbSlicer());
But if you would like to make the code as modular as possible you can use this method to perform an unchecked cast (pure evil some say) and get the result you want:
public static void main(String[] args) {
ItemSlice slice = getMySlice(new DynamoDbItemService());
}
#SuppressWarnings("unchecked")
public static <T extends Slicer, E extends ItemSlice> E getMySlice(ItemService<T, E> service) {
return service.getItemHistory("", (T) new DynamoDbSlicer());
}
And then of course there is the solution of passing the type inference responsibility to the actual field that is storing the value. I myself would go for this solution, as I think it offers the most flexibility:
public class DynamoDbItemService<T extends Slicer, E extends ItemSlice> implements ItemService<T, E>
ItemService<DynamoDbSlicer, DynamoDbItemSlice> itemService = new DynamoDbItemService();
ItemSlice slice = itemService.getItemHistory("", new DynamoDbSlicer());
I'm really confused of how upper bounded types work in Java generics.
Let's say I have
interface IModel<T>
interface I
class A implements I
class B implements I
class C implements I
then I have a method with parameter as follows
foo(IModel<Map<? extends I, Map<? extends I, List<? extends I>>>> dataModel)
calling that method like
IModel<Map<A, Map<B, List<C>>>> model = ...
foo(model)
ends with compilation error
Error:(112, 49) java: incompatible types: IModel<java.util.Map<A,java.util.Map<B,java.util.List<C>>>> cannot be converted to IModel<java.util.Map<? extends I,java.util.Map<? extends I,java.util.List<? extends I>>>>
I have read docs about Java generics from the Oracle web, trying to google it, but there must be something I totally misunderstood.
This question can be shorted as why
foo(IModel<List<? extends I>> dataModel)
can not accept argument like
IModel<List<A>> model
Explanation
List<A> is a subtype of List<? extends I>, so it is ok:
public void bar(List<? extends I> list);
List<A> listA;
bar(listA);
But, it does not make IModel<List<A>> a subtype of IModel<List<? extends I>>, just like IModel<Dog> is not a subtype of IModel<Animal>, so the code you posted can not be compiled.
Solution
You can change it to:
foo(IModel<? extends Map<? extends I, ? extends Map<? extends I, ? extends List<? extends I>>>> dataModel)
or
<FIRST extends I, SECOND extends I, THIRD extends I> void foo(IModel<Map<FIRST, Map<SECOND, List<THIRD>>>> dataModel)
to make it compile.
First of all, I wonder how much effort it would have been for you (one person) to sort out the code to be in this form:
import java.util.List;
import java.util.Map;
interface IModel<T> {}
interface I {}
class A implements I {}
class B implements I {}
class C implements I {}
public class UpperBounds
{
public static void main(String[] args)
{
IModel<Map<A, Map<B, List<C>>>> model = null;
foo(model);
}
static void foo(IModel<Map<? extends I, Map<? extends I, List<? extends I>>>> dataModel)
{
}
}
instead of letting hundreds of people (who want to help you) do this on their own, in order to have something that they can compile and have a look at in their IDE. I mean, it's not that hard.
That being said: Technically, you're missing a few more extends clauses here. This compiles fine:
import java.util.List;
import java.util.Map;
interface IModel<T> {}
interface I {}
class A implements I {}
class B implements I {}
class C implements I {}
public class UpperBounds
{
public static void main(String[] args)
{
IModel<Map<A, Map<B, List<C>>>> model = null;
foo(model);
}
static void foo(IModel<? extends Map<? extends I, ? extends Map<? extends I, ? extends List<? extends I>>>> dataModel)
{
}
}
But you should
not
implement it like that. That's obscure. Whatever this dataModel parameter is, you should consider creating a proper data structure for that, instead of passing along such a mess of deeply nested generic maps.
The reason of why the original version did not compile was already mentioned in other answers. And it can be made clearer by showing an example using a much simpler method call. Consider this example:
interface IModel<T> {}
interface I {}
class A implements I {}
class B implements I {}
class C implements I {}
public class UpperBounds
{
public static void main(String[] args)
{
List<List<A>> lists = null;
exampleA(lists); // Error
exampleB(lists); // Works!
}
static void exampleA(List<List<? extends I>> lists)
{
}
static void exampleB(List<? extends List<? extends I>> lists)
{
}
}
The exampleA method cannot accept the given list, whereas the exampleB method can accept it.
The details are explained nicely in Which super-subtype relationships exist among instantiations of generic types? of the generics FAQ by Angelika Langer.
Intuitively, the key point is that the type List<A> is a subtype of List<? extends I>. But letting the method accept only a List<List<? extends I>> does not allow you to pass in a list whose elements are subtypes of List<? extends I>. In order to accept subtypes, you have to use ? extends.
(This could even be simplified further: When a method accepts a List<Number>, then you cannot pass in a List<Integer>. But this would not make the point of List<A> being a subtype of List<? extends I> clear here)
Having a method method1(Map<I> aMap>) and A being a class implementing I doesn't allow you to call the method with a Map<A> and that's for a reason.
Having the method:
public static void foo2(IModel<I> dataModel) {
System.out.println("Fooing 2");
}
Imagine this code:
IModel<A> simpleModel = new IModel<A>() {};
foo2(simpleModel);
This shouldn't work because you supply a more specific type to a method that requires a generic type. Now imagine foo2 does the following:
public static void foo2(IModel<I> dataModel) {
dataModel = new IModel<B>() {};
System.out.println("Fooing 2 after we change the instance");
}
Here you will try to set IModel to IModel which is valid - because B extends I, but if you were able to call that method with IModel it wouldn't work
Create your model like:
IModel<Map<I, Map<I, List<I>>>> model = ...
and in the corresponding maps and lists add objects of type A, B and C which will be valid and then call the function foo(model)
There is technique to define class, containing a method, returning a value of the same type as class -- self recursion.
But using this, is it possible to stop recursion?
Some code:
public class StopSelfRecursion {
// base class
static class Class1<Self extends Class1<Self,T>, T> {
public Self getMyself() {
return (Self) this;
}
}
// derived 1
static class Class2<Self extends Class2<Self, T>, T> extends Class1<Self, T> {
}
// derived 2
static class Class3<Self extends Class2<Self, T>, T> extends Class2<Self, T> {
}
// want to stop recursion; want Class4 has only one parameter
static class Class4<T> extends Class3<Class3, T> {
}
public static void main(String[] args) {
Class1<?, Integer> v1 = new Class1<>();
Class2<?, Integer> v2 = new Class2<>();
Class3<?, Integer> v3 = new Class3<>();
System.out.println(v1.toString());
System.out.println(v2.toString());
System.out.println(v3.toString());
}
}
If it is not possible to stop recursion, then why?
If there is no logic reason of being not able to stop it, then what about adding this feature in next versions of Java?
For example, keyword ThisClass can be added or something.
I'm not 100% clear what the issue is, beyond fixing the compilation issue. You can do that by simply changing the definition of Class4 to this:
static class Class4<T> extends Class3<Class4<T>, T>
^^
[Live example]
I have an interesting discrepancy between javac and Eclipse IDE compiler, and can't figure out who's right. So, the code below compiles with javac, however Eclipse tells me that the static initializer's invocation of "exportAll" is wrong, 'cause:
The method exportAll(Iterable< X.Stat< ? extends Number>>) in the type X is not applicable for the arguments (Collection< capture#1-of ? extends X.Stat>)
Who's right? javac or Eclipse?
import java.util.Map;
public class X {
interface Stat<T> {
}
public static void exportAll(Iterable<Stat<? extends Number>> vars) {
}
public static Map<Double, ? extends Stat> getPercentiles() {
return null;
}
static {
exportAll(getPercentiles().values());
}
}
You can't compile your example - you are calling a non-static method getPercentiles from the static initializer, so I'll assume that it is a static method, too.
In any case, your compiler would at least spit out an "unchecked" warning if you compile with -XLint:unchecked (Stat takes a type parameter!). I assume you would like the following:
public class X {
interface Stat<T> {
}
public static void exportAll(Iterable<? extends Stat<? extends Number>> vars) {
}
public static Map<Double, ? extends Stat<Double>> getPercentiles() {
return null;
}
static {
exportAll(getPercentiles().values());
}
I assume that your percentiles are an arbitrary subclass of Stat<Double>, therefore I declared them as ? extends Stat<Double> in the Map. So the values() call will return a Collection<? extends Stat<Double>>.
Collection implements Iterable, therefore we are safe on that side.But Collection<? extends Stat<Double>> is not covered by Iterable<Stat<? extends Number>>, therefore we need to declare the argument as Iterable<? extends Stat<? extends Number>>.
The beauty (well, except for the syntax) of having exportAll take Iterable<? extends Stat<? extends Number>> is that your Map could contain all sorts of ? extends Stats<N> where N is a subclass of Number.
Your Map<Double, ? extends Stat>.values() will have a type of Collection<? extends Stat>. This Stat is really Stat<?>. Your Iterable requires that the Stat not just be any old Stat<?> but rather Stat<? extends Number>. You would have to change your getPercentiles() to be Map<Double, ? extends Stat<? extends Number>>.
public static void exportAll(Iterable<Stat<? extends Number>> vars) {
} // ^ this must match
// your values type on the map
public Map<Double, ? extends Stat<? extends Number>> getPercentiles() {
return null;
}
#emboss here's what I would do in those cases whenever I could:
class Main {
static interface Something<E> {
void doSomething();
}
static class ConcreteSomething<E> implements Something<E> {
E data;
ConcreteSomething(E data) {
this.data = data;
}
public void doSomething() {
System.out.println(data);
}
}
public static void main(String[] args) {
List<Something<Number>> list = new LinkedList<Something<Number>>();
list.add(new ConcreteSomething<Number>(Math.PI)); // an autoboxed Double
list.add(new ConcreteSomething<Number>(new Integer(5))); // an Integer
for(Something<Number> s : list) s.doSomething();
}
}
It doesn't compile in javac. (after adding static to getPercentiles)
Get your facts straight; don't waste other people's time.
Kids today, too much ADD.
I have a class
public abstract class AbstractE<T, E extends Enum<E> & Flags>
{
public interface Flags{} /*marker interface*/
//...
//other code
}
and an interface
public interface IXYZAdapter
{
public <E extends Enum<E> & Flags> Set<E> getFlags();
}
Where Flags is an interface defined in AbstractE itself.
M extends AbstractE thus:
public class M extends AbstractE<Long, M.EF> implements IXYZAdapter
{
public enum EF implements AbstractE.Flags{flag1, flag2}
#Override /*from IXYZAdapter*/
public Set<M.EF> getFlags()
{return EnumSet.allOf(EF.class);}
}
Now, from the main code, I try to get a handle on the interface IXYZAdapter and invoke the getFlags method
IXYZAdapter adapter = (IXYZAdapter)m; //where m is an instance of AbstractE
Set s = adapter.getFlags();
I get the following compile time error in the main program last line (Set s = adapter.getFlags();)
invalid inferred types for E; inferred type does not conform to declared bound(s)
inferred: AbstractE.Flags
bound(s): java.lang.Enum<AbstractE.Flags>,AbstractE.Flags
What am I doing wrong?
I am using Java 6
Edited to specify the error location
Try this:
public interface IXYZAdapter <E extends Enum<E> & AbstractE.Flags>
{
public Set<E> getFlags();
}
And
public class M extends AbstractE<Long, M.EF> implements IXYZAdapter<M.EF>
{
}
Or
Set<M.EF> s = adapter.getFlags();
The problem is that with Set s = adapter.getFlags(); The system doesn't know which type to infer for E in IXYZAdapter and thus the E in AbstractE doesn't match.
Edit:
Another option might be:
interface IXYZAdapter <E extends Enum<E> & AbstractE.Flags>
{
public Set<? extends E> getFlags();
}
class M extends AbstractE<Long, M.EF> implements IXYZAdapter<M.EF>
{
public enum EF implements AbstractE.Flags{flag1, flag2}
public Set<? extends M.EF> getFlags()
{return EnumSet.allOf(EF.class);}
}
And the call: Set<? extends AbstractE.Flags> s = adapter.getFlags();
This would allow you to get a set of flags without casting and force the flags to be declared as enum.
using the first solution thomas provided, the main method can be written like this to become warning free without actually having to know about the enum type:
public static void main(String[] args) {
M m = new M();
IXYZAdapter<?> adapter = (IXYZAdapter<?>)m;
Set<?> flags = adapter.getFlags();
Iterator<?> it = flags.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}