T延伸SomeClass有什么意义? [英] What is the point of T extends SomeClass?
本文介绍了T延伸SomeClass有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这样的方法声明有什么区别:
public< T extends SomeClass> void doSomething(T obj)
{
//做某事。
}
与此:
public void doSomething(SomeClass obj)
{
//做某事。
}
我看到它的方式,它们都指定传入的对象 must 是类型 SomeClass
的子类,那么为什么还要在这个实例中使用泛型?
但请考虑以下几点:
public< T extends SomeClass> void doSomething(List< T> obj)
在这种情况下,您可以通过以下方式调用该方法:
obj.doSomething(new ArrayList< SubclassOfSomeClass>());
obj.doSomething(new ArrayList< SomeClass>());
如果您使用
public void doSomething(List< SomeClass> obj)
能够做到这一点:
obj.doSomething(new ArrayList< SomeClass>());
What is the difference with a method declaration like this:
public <T extends SomeClass> void doSomething(T obj)
{
// Do something.
}
And this:
public void doSomething(SomeClass obj)
{
// Do Something.
}
The way I see it, both of them are specifying that the object passed in must be a subclass of type SomeClass
, so why bother with the generics at all in this instance?
解决方案
In your case it doesn't make much difference.
But consider the following:
public <T extends SomeClass> void doSomething(List<T> obj)
In this case you could call the method the following ways:
obj.doSomething(new ArrayList<SubclassOfSomeClass>());
obj.doSomething(new ArrayList<SomeClass>());
If you would use
public void doSomething(List<SomeClass> obj)
You would only be able to do this:
obj.doSomething(new ArrayList<SomeClass>());
这篇关于T延伸SomeClass有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文