为什么/何时应使用通用方法? [英] Why/when should generic methods be used?

查看:98
本文介绍了为什么/何时应使用通用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习Java,我遇到过通用方法.

Studying Java, I've come across generic methods.

public <T> void foo(T variable) { }

也就是说,该方法采用未确定类型的参数(PHP吗?).但是,我看不到这将是一个很好的解决方案-特别是因为我从一门松散的语言中逐渐爱上了一种强类型的语言.

That is, a method which takes a parameter with an undecided type (á la PHP?). I'm however unable to see how this would be a good solution - especially since I've come to fall in love with a strongly typed languages after coming from a loose ones.

是否有使用通用方法的理由?如果是这样,什么时候?

Is there any reason to use generic methods? If so, when?

推荐答案

泛型除其他外,还为您提供了一种提供模板的方法-即您想做相同的事情,唯一的区别是类型.

Generics, among other things, give you a way to provide a template -- i.e. you want to do the same thing, and the only difference is the type.

例如,查看列表API ,您将看到方法

For example, look at the List API, you will see the methods

add(E e)

对于您声明的每个相同类型的列表,add方法的唯一不同之处在于进入列表的事物的类型.这是泛型有用的主要示例. (在将泛型引入Java之前,您需要声明一个列表,并且可以向列表中添加任何内容,但是检索到该对象时必须转换对象)

For every list of the same type you declare, the only thing different about the add method is the type of the thing going into the list. This is a prime example of where generics are useful. (Before generics were introduced to Java, you would declare a list, and you could add anything to the list, but you would have to cast the object when you retrieved it)

更具体地说,您可能需要2个ArrayList实例,一个实例使用type1,另一个实例使用type2. add的列表代码将对每个列表执行相同的操作,执行相同的代码(因为两个列表都是ArrayList实例),对吗?因此,唯一不同的是列表中的内容.

More specifically, you might want 2 ArrayList instances, one that takes type1 and one that takes type2. The list code for add is going to do the same thing, execute the same code, for each list (since the two lists are both ArrayList instances), right? So the only thing different is what's in the lists.

(@ michael指出,add不是通用方法的真实示例,但是链接的API中存在真实的通用方法,并且概念相同)

(As @michael points out, add isn't a true example of a generic method, but there are true generic methods in the API linked, and the concept is the same)

这篇关于为什么/何时应使用通用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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