Foo <?,?,?> Not Foo <?,?,?>

I have a very simple method that I cannot work with:

private Map<UUID, Foo<?, ?, ?>> foos = new HashMap<UUID, Foo<?, ?, ?>>();

public Optional<Foo<?, ?, ?>> getFoo(UUID id){
    return Optional.fromNullable(foos.get(id)); //Type mismatch: cannot convert from Optional<Action<capture#31-of ?,capture#32-of ?,capture#33-of ?>> to Optional<Action<?,?,?>>
}

How can these be incompatible types? How can I get around this?

+4
source share
4 answers

Your code compiles in Java 8. ( Optional.fromNullablemethod from Guava ).

But it does not compile in Java 7, where I get your compiler error.

Java 8 has improved target type output .

. Java . - , Java, , . , Java SE 7. Java SE 8 .

Java 7, fromNullable.

return Optional.<Foo<?, ?, ?>>fromNullable(foos.get(id));

Java 8, .

( Java 8, Guava, Java 8 Optional.ofNullable).

+4

.

Optional.<Foo<?, ?, ?>>fromNullable(foos.get(id))
0

You may need to use Optional<? extends Foo<?, ?, ?>>. Other? having different meanings become weird, but this approach often works.

0
source

Wildcard objects (at least in Java 7) cannot be modified; you can extract data from it.

For example, you can:

 public void example( List<?> myList1, List<?> myList2 ){
    myList1.get(0); //this works
    myList1.add( myList2.get(0) );
 }

So, can the method you call modify the object inside?

0
source

All Articles