Java泛型,使用&lt ;?扩展超类&GT,澄清需要

编程入门 行业动态 更新时间:2024-10-27 01:34:37
本文介绍了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 将允许您在处理各种不同的子类时处理情况。

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

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,澄清需要

本文发布于:2023-11-17 11:37:56,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:泛型   Java   amp   GT   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!