为什么/何时应使用通用方法?

编程入门 行业动态 更新时间:2024-10-26 06:33:53
本文介绍了为什么/何时应使用通用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

学习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)

更多推荐

为什么/何时应使用通用方法?

本文发布于:2023-11-03 06:29:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554454.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时应   方法

发布评论

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

>www.elefans.com

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