generics error: not applicable for the arguments

安稳与你 提交于 2019-11-27 09:42:52

The answer is simple: the unbound wildcard cannot be used. It simply means "uknown object".

It doesn't give anything informative to compiler. "?" means of whatever type, so actually it is too generic to mean anything.

Take a look here: http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html

As stated:

Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error

Since we don't know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.

EDIT: don't worry, this is a normal misunderstanding of java wildcard when you start using them. That's why bounded wildcards (eg. <? extends Something>) exist, otherwise generic wildcard would be almost useless since compiler cannot make any assumptions on it.

That does not work because your class Client is written for no specific Strategy (Strategy<?>) but in the run() method, you pass a String (which is only correct for Strategy<String>!). That would only work if you'd change a's type and setStrategy()'s parameter to the type Strategy<String>!

This is because this is not a type safe operation. "?" is a wildcard that means I do not know the type. It does not mean "any type". read this... http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!