The difference between void foo (t y) and void foo (t y) in Java generic classes

Explain in detail the differences (if any) between the following two versions of Java generic classes?

class C<T>{
    T x;
    void foo(T y)  { … }
}

and

class C<T>{
    T x;
    <T> void foo(T y)  { … }
}

Another question: what can be written in the body of foo () to replace the "..." that causes the java compiler to accept the first version of C but reject the second version of C

I'm confused

Solution

class C<T>{
class C<T>{
    T x;
    <T> void foo(T y)  { … }
}

Is a confusing way of writing

class C<T>{
    T x;
    <S> void foo(S y)  { … }
}

As for what will reject the second version, for example:

class C<T>{
    T x;
    <T> void foo(T y)  { x = y; }
}

Will fail because if you rewrite it as

class C<T>{
    T x;
    <S> void foo(S y)  { x = y; }
}

You can immediately see that you missed the cast (the exact compiler error is "incompatible type")

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
分享
二维码
< <上一篇
下一篇>>