generic and non-generic with the same name
The java api defines several generics and non-generics with the same name - like LinkedList
etc. They are both resoled using the same statement import java.util.LinkedList;
. But in one package, only one public class may be present in .java file(with the same name).
So can we get the same effect? I tried the following code:
package org.****.ai.ass1.part1;
import java.util.LinkedList;
public abstract class Test extends LinkedList { }
//public abstract class Test<E> extends LinkedList<E> { }
Without the comment开发者_如何学Go, I get the following error : The type Test is already defined
. However both the lines compile if I comment the other one. So how does the java api do it?
Due to the way Java implements generics (Google for type erasure), LinkedList<T>
and LinkedList
represent exactly the same type. There is no way to declare two different types, one generic and one not, with the same fully-qualified name.
It's probably because you are looking at both the Java API for a class before 1.5, when generics were added, and the same API 1.5 and later.
Like java.util.List
as of Java 1.4, and List 1.5.
Like you said, they share the same name, except the second one has the generic type parameter .
In Java 1.5, or Java 5, they rewrote many of the collection classes, like List, Iterator, HashMap, etc. to include generic type parameters. So they don't have two versions of one class in the core Java libraries, they just rewrote them to take advantage of the type safety provided by generics at compile time.
However, thanks to type erasure, the generic version of List is just like the normal version of List, for backwards compatibility purposes. A List<String>
ends up just like a List
.
If you define a class like this:
package x;
public class Clazz<T> {
}
you can use it as a generic and a non-generic class as well:
public class X extends x.Clazz {
}
public class Y extends x.Clazz<String> {
}
精彩评论