Java – contains type inference for return types, wildcards, and cross types
•
Java
I'm trying to declare an interface that contains a method that will return an implementation comparator < Object > and action, that is
<T extends Comparator<Object> & Action> List<T> getThings();
This compilation is good, but when I try to call this method, a problem occurs I want to do this:
List<Action> things = getThings(); List<Comparator<Object>> things = getThings();
When I try to do this, I get the following compilation errors:
incompatible types; no instance(s) of type variable(s) T exist so that java.util.List<T> conforms to java.util.List<javax.swing.Action> found : <T>java.util.List<T> required: java.util.List<javax.swing.Action>
The following are also invalid:
List<? extends Action> things = getThings(); List<? extends Comparator<Object>> things = getThings();
Another way to achieve this effect is to create an empty interface that uses comparator < Object > and action as return types, that is
public interface ComparatorAction extends Comparator<Object>,Action { } List<ComparatorAction> getThings();
But I don't want to There must be a way to do what I want, right? Any ideas?
thank you!
PS: I have a hard time proposing a good title for this position, so change it at any time
Solution
You can also parameterize the method that calls getthings () For example:
public static <U extends Comparator<Object> & Action> void main(String[] args) { List<U> l = getThings(); Action a = l.get(0); Comparator<Object> c = l.get(0); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码