سؤال

Explain in detail the difference, if any, between the following two versions of a Java generic class?

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

and

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

and another question: What could be written in the body of foo(), replacing the “…” that would cause the Java compiler to accept the first version of C but reject the second version of C.

I'm very puzzled.

هل كانت مفيدة؟

المحلول

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

is a confusing way to write

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

as for what would reject the second version, for example this:

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're missing a cast (the exact compiler error is "incompatible types").

نصائح أخرى

In the first example, the T type variable in the method foo represents the very same type that is declared in the class definition C<T>.

The second example is a pitfall, because the T in the method declaration is a completely different type unrelated to the type parameter of the class, it just happens to have the same name T. It is a similar case to the situation when a local variable hides a field of the same name.

Eclipse emits a nice compiler warning (if this warning is turned on in the settings, not sure if it is on by default) for this situation:

The type parameter T is hiding the type T

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top