泛型构造函数的一个目的可以与某些泛型方法相同:确保多个参数引用相同的类型.
考虑以下示例(是的,它有点做作,但应该表明这一点):
import java.util.ArrayList;
import java.util.Collection;
public class GenericConstructorTest
{
public static void main(String[] args)
{
Collection strings = new ArrayList();
ClassWithParam c0 = new ClassWithParam("String", strings);
}
}
class ClassWithParam
{
public ClassWithParam(T data, Collection collection)
{
collection.add(data);
}
}
类或其构造函数在那里使用的类型无关紧要.重要的是要知道作为第二个参数给出的集合可以采用作为第一个参数给出的类型的元素.
(我想展示一个更现实,实用的例子,但是认为很少有必要以这种方式参数化构造函数,甚至可以认为这只是参数化方法的一个“副作用”,并且事实上,没有理由明确禁止这对于构造函数……)
编辑根据评论中的请求,以及通常使用给定参数的示例.它仍然相当做作.更现实的例子可能在结构上相似并且引用了某些类型的侦听器,但是会涉及更多的代码:
public class GenericConstructorTest
{
public static void main(String[] args)
{
Callback callback = new Callback();
ClassWithParam c0 = new ClassWithParam("String", callback);
c0.execute();
}
}
class ClassWithParam
{
private Runnable runnable;
public ClassWithParam(final T data, final Callback callback)
{
runnable = new Runnable()
{
@Override
public void run()
{
callback.call(data);
}
};
}
void execute()
{
runnable.run();
}
}
class Callback
{
void call(T t)
{
System.out.println("Called with "+t);
}
}
您发布的第二个示例
Integer val = new Integer(100);
不能用Java 7在Eclipse中编译.它抱怨道
The constructor Integer(int) of type Integer is not generic; it cannot be parameterized with arguments
在Java 8中,这是允许的,尽管它仍然会发出警告:
Unused type arguments for the non generic constructor Integer(int) of type Integer; it should not be parameterized with arguments
(如果这个差异是你真正感兴趣的,你可以考虑将其作为一个单独的问题)