Java泛型,使用&lt ;?扩展超类&GT,澄清需要 [英] Java generics, using <? extends Superclass>, clarification needed

查看:107
本文介绍了Java泛型,使用&lt ;?扩展超类&GT,澄清需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设

  A延伸X 

您需要对对象执行一些操作。执行操作的方法可能是:

pre $ public void doMagic(List< ;? extends X> e)

或者,您可以选择致电它

  public void doMagic2(List< X> e)

您要求魔术完成:

 列表< X> ; listOfA = new ArrayList< X>(); 
listOfA.add(new A());

C c = new C();
c.doMagic(listOfA); //按预期工作
c.doMagic2(listOfA); //按预期工作

你能描述为什么一种方法比另一种方法更受欢迎,何时应该使用

如果是 List< lt; code> ;?它会接受 X 列表和 X X 接口或者 X 的所有实现c>。



一个优于另一个,?扩展X 将允许您在处理各种不同的子类时处理情况。



一个例子是一个函数例如计算文件的大小(以字节为单位):

  public int getTotalSizeInBytes(List< ;? extends File> files){




$ b现在这个函数可以计算大小而不管文件类型可以是 plainTextFile excelFile wordFile databaseFile 等。


Suppose

    A extends X

You need to perform some operation on object either A. Method performing the operation may be:

    public void doMagic(List<? extends X> e) 

Alternatively, you may chose to call it

    public void doMagic2(List<X> e) 

You ask for magic to be done by:

    List<X> listOfA = new ArrayList<X>();
    listOfA.add(new A());

    C c = new C();
    c.doMagic(listOfA);   // works as expected
    c.doMagic2(listOfA);  // works as expected

Can you describe why one approach is preferred over another and when it should be used please?

解决方案

In case of List<X> as you can guess, it would work with objects of type X only.

In case of List<? extends X>, it would accept a list of X and all the sub-classes of X or all the implementations of X if X was an interface.

The benefits of one over the other, well, ? extends X would allow you to take care of situation when you want to handle all sorts of different sub classes.

An example would be a function that calculates, say, size in bytes of files:

public int getTotalSizeInBytes(List<? extends File> files) {
...
}

Now this function can go about calculating the size regardless of the file type which can be plainTextFile, excelFile, wordFile, databaseFile etc.

这篇关于Java泛型,使用&lt ;?扩展超类&GT,澄清需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆