简体   繁体   English

对Java规范中的泛型子类型感到困惑吗?

[英]Confusion over generics subtyping in java specs?

I'm reading java specs https://docs.oracle.com/javase/specs/jls/se10/html/jls-4.html#jls-4.10.2 and this line confuses me: 我正在阅读Java规范https://docs.oracle.com/javase/specs/jls/se10/html/jls-4.html#jls-4.10.2 ,此行使我感到困惑:

D<U1 θ,...,Uk θ> , where D<U1,...,Uk> is a generic type which is a direct supertype of the generic type C and θ is the substitution [F1:=T1,...,Fn:=Tn]. D<U1 θ,...,Uk θ> ,其中D<U1,...,Uk>是泛型,它是泛型C的直接超类型,而θ是替换[F1:= T1,。 ..,FN:= Tn的]。

is Uk θ here casting? Uk θ在这里铸造吗? and after substitution D becomes D<(U1)T1,...,(Uk)Tk> ? 并且替换D成为D<(U1)T1,...,(Uk)Tk> If so why does the author omit the brackets in Uk θ as part of casting syntax? 如果是这样,为什么笔者省略括号Uk θ铸造语法的一部分? Thanks! 谢谢!

Not casting. 不投 It's the mathy language used to describe a type. 这是用来描述类型的数学语言。

In code, it's saying that if: 在代码中,这意味着:

interface D<A, B> {}
interface C<A, B> extends D<A, B> {}

class Y implements D<String, Number> {}
class X implements C<String, Integer> {} // Note Integer is a subtype of Number

Then this compiles: 然后编译:

D d = new X();

Given a generic type declaration C<F1,...,Fn> (n > 0), the direct supertypes of the parameterized type C<T1,...,Tn> , where Ti (1 ≤ i ≤ n) is a type, are all of the following: 给定通用类型声明C<F1,...,Fn> (n> 0),则参数化类型C<T1,...,Tn>的直接超类型其中Ti(1≤i≤n)为类型,以下所有内容:

D<U1 θ,...,Uk θ> , where D<U1,...,Uk> is a generic type which is a direct supertype of the generic type C<F1,...,Fn> and θ is the substitution [F1:=T1,...,Fn:=Tn]. D<U1 θ,...,Uk θ> ,其中D<U1,...,Uk>是泛型,它是泛型C<F1,...,Fn>的直接超类型,θ为替换[F1:= T1,...,Fn:= Tn]。

Let us see an example. 让我们来看一个例子。

public class D<U1,U2> {
}

//Note the order of F3,F4.
class C<F1,F2,F3,F4> extends D<F4,F3>{

}

class Main{

    public static void main(String[] args) {

        C<Integer,String,Float,Number> obj = new C<>();

        D<Float ,Number> obj2 = obj; // Compilation error

        D<Number ,Float> obj3 = obj; //This is fine


    }
}

What do you think θ is here ? 您认为θ在这里?

θ = [F1:= Integer , F2:= String, F3:= Float, F4:= Number ] θ = [F1:=整数,F2:=字符串,F3:=浮点,F4:=数字]

Now D<Number,Float> is the correct supertype. 现在D<Number,Float>是正确的超类型。 But not D<Float,Number> . 但不是D<Float,Number> Why ? 为什么呢

Because of Ui θ . 由于Ui θ So what does this mean ? 那么这是什么意思 ?

Well , it just means substitute ie Scan U1 , U2 , ... till Uk and if you find any Fi , then replace it by Ti . 好吧,这仅表示替代,即扫描U1 , U2 , ... till Uk ,如果找到任何Fi ,则将其替换为Ti

In our example , it means Scan F4 and F3 of class D. Did you have F4 and F3 in θ ? 在我们的示例中,这意味着扫描D类的F4F3 。您在θ中有F4F3吗? Yes. 是。 Then F4 , F3 of D have to be as defined in θ . 然后, D F4F3 必须θ所定义。

Note : The answer is as per my understanding. 注意 :答案是根据我的理解。 I don't have any concrete reference of what Uk θ means in Java type semantics. 关于Java类型语义中Uk θ含义,我没有任何具体参考。

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

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