简体   繁体   English

当类具有绑定的类型参数时使用绑定的通配符

[英]Using bounded wildcard when class has bounded type parameters

Suppose I have a class 假设我有一堂课

public static class A<T extends D> { ... }

and the class D with two classes extending it: B and C , eg D类具有两个扩展它的类: BC ,例如

public static class D { ... }
public static class B extends D { ... }
public static class C extends D { ... }

Now, at some place let's say I want an array of A 's, irrespective of being of the B -kind or the C -kind. 现在,在某个地方,无论我是B型还是C型,我都想要一个A数组。 (And apply functions from class D to all items in the array, for example.) (例如,将类D函数应用于数组中的所有项目。)

Should I then constrain the type again ? 如果我还是那句话约束类型?

In other words: which of these options is the one to go with? 换句话说:哪个选项可供选择?

  1. A<?>[] re;

  2. A<? extends D>[] re;

Which one is best practice? 哪个是最佳做法?

Since T has an upper bound of D , A<?> is just a shorthand for A<? extends D> 由于T的上限为D ,所以A<?>只是A<? extends D>的简写A<? extends D> A<? extends D> . A<? extends D> They both mean the same thing - just like if T were unbounded, A<?> would be short for A<? extends Object> 它们都具有相同的含义-就像T是无界的一样, A<?>将是A<? extends Object>缩写A<? extends Object> A<? extends Object> . A<? extends Object>

I don't know of any best practice when it comes to this syntax; 对于这种语法,我不知道有任何最佳实践。 I think it's just a matter of coding style. 我认为这只是编码风格的问题。 I would prefer A<?> because it's concise, though A<? extends D> 我更喜欢A<?>因为它很简洁,尽管A<? extends D> A<? extends D> immediately communicates the upper bound to a developer unfamiliar with A . A<? extends D>立即将上限传达给不熟悉A的开发人员。

According to me you should go with A<? extends D>[] re; 根据我的说法,你应该选择A<? extends D>[] re; A<? extends D>[] re; So that user will not allow you to add only object which extends class D bounded wildcards provides limited flexibility within bound. 因此,该用户将不允许您仅添加扩展了D类有界通配符的对象,从而限制了绑定范围内的灵活性。

Any Type with bounded wildcards can only be instantiated within bound and any instantiation outside bound will result in compiler error.One of the important benefit of using bounded wildcard is that it not only restrict number of Type can be passed to any method as argument it also provides access to methods declared by bound. 任何带有带界通配符的Type都只能在bound内实例化,而带界外的任何实例化都将导致编译器错误。使用带界通配符的重要好处之一是,它不仅限制Type的数量,还可以作为参数传递给任何方法,而且提供对bound声明的方法的访问。 for example TreeMap( Comparator<? super K> comparator ) allows access to compare() method of Comparator in Java. 例如TreeMap( Comparator<? super K> comparator )允许访问Java中Comparator的compare()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM