Java泛型Puzzler,扩展一个类并使用通配符 [英] Java Generics Puzzler, extending a class and using wildcards
问题描述
import java.util。*;
class Tbin< T>扩展ArrayList< T> {}
class TbinList< T>扩展ArrayList< Tbin< T>> {}
class Base {}
class Derived extends Base {}
$ b public class Test {
public static void main(String [] args) {
ArrayList< Tbin<扩展Base>> test = new ArrayList<>();
test.add(new Tbin< Derived>());
TbinList <?扩展Base> test2 = new TbinList<>();
test2.add(new Tbin< Derived>());
$ / code $ / pre
使用Java 8.它在我看来就像直接在 test
中创建容器等同于 test2
中的容器,但编译器说: b.b
Test.java:15:error:找不到添加的合适方法(Tbin< Derived>)
test2.add(new Tbin<衍生GT;());
$
如何写 Tbin
和 TbinList
所以最后一行可以接受?
请注意,我实际上会添加键入 Tbin
s这就是为什么我在最后一行指定 Tbin< Derived>
的原因。
解决方案好的,这里是答案:
import java.util。* ;
class Tbin< T>扩展ArrayList< T> {}
class TbinList< T>扩展ArrayList< Tbin<延伸T>> {}
class Base {}
class Derived extends Base {}
$ b public class Test {
public static void main(String [] args) {
TbinList< Base> test3 = new TbinList<>();
test3.add(new Tbin< Derived>());
$ b code
$ b $ p $正如我所预料的那样,一旦我看到它。但是很多人为了到这里而th ing不安。 Java的泛型看起来很简单,如果你只看代码。
感谢大家,作为一个声音板。
I've been beating my head against this one for awhile and thought that maybe some fresh eyes will see the issue; thanks for your time.
import java.util.*;
class Tbin<T> extends ArrayList<T> {}
class TbinList<T> extends ArrayList<Tbin<T>> {}
class Base {}
class Derived extends Base {}
public class Test {
public static void main(String[] args) {
ArrayList<Tbin<? extends Base>> test = new ArrayList<>();
test.add(new Tbin<Derived>());
TbinList<? extends Base> test2 = new TbinList<>();
test2.add(new Tbin<Derived>());
}
}
Using Java 8. It looks to me like the direct creation of the container in test
is equivalent to the container in test2
, but the compiler says:
Test.java:15: error: no suitable method found for add(Tbin<Derived>)
test2.add(new Tbin<Derived>());
^
How do I write Tbin
and TbinList
so the last line is acceptable?
Note that I will actually be adding typed Tbin
s which is why I specified Tbin<Derived>
in the last line.
解决方案 OK, here's the answer:
import java.util.*;
class Tbin<T> extends ArrayList<T> {}
class TbinList<T> extends ArrayList<Tbin<? extends T>> {}
class Base {}
class Derived extends Base {}
public class Test {
public static void main(String[] args) {
TbinList<Base> test3 = new TbinList<>();
test3.add(new Tbin<Derived>());
}
}
As I expected, kind of obvious once I saw it. But a lot of thrashing around to get here. Java generics seem simple if you only look at working code.
Thanks, everyone, for being a sounding board.
这篇关于Java泛型Puzzler,扩展一个类并使用通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!