括号内和括号外的Java通用方法参数类型 [英] Java generic method parameter type inside brackets vs. outside brackets

查看:75
本文介绍了括号内和括号外的Java通用方法参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间是否有任何区别

Is there any difference between:

static void findMax(LinkedList<? extends Number> list){...}

和:

static <T extends Number> void findMax(LinkedList<T> list){...}

由于两者都有效,所以我想知道两者之间是否有较大的区别,建议使用.

Since both work, I'd like to know if there's any big difference between the two and which is advised.

推荐答案

主要区别在于,在第二个版本中,您可以访问类型T,而在第一个版本中,您不能访问类型.

The main difference is that in the second version you can access the type T whereas in the first one you can't.

例如,您可能想返回链接到T的内容(例如,返回T而不是void):

For example, you might want to return something linked to T (e.g. returning T instead of void):

static <T extends Number> T findMax(LinkedList<T> list){...}

或者您可能需要创建一个新的Ts列表:

Or you might need to create a new list of Ts:

static <T extends Number> void findMax(LinkedList<T> list){
    List<T> copyAsArrayList = new ArrayList<> (list);
    //do something with the copy
}

如果您不需要访问T,则两个版本在功能上都是等效的.

If you don't need access to T, both versions are functionally equivalent.

这篇关于括号内和括号外的Java通用方法参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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