简单的 Java 重写方法
我想知道是否可以以更简单的方式重写 Java 方法。我的基本问题是我有一组方法,一个例子可以是计算值数组的平均值。我的问题是我想让这个方法适用于所有数字变量类型(int long double float等)除了创建之外还有什么方法可以做到这一点:
- 为每个参数类型提供一个新方法
- 让这些新方法调用一个基本方法已解析的参数
如有任何帮助,我们将不胜感激。
在查看答案时,我注意到我一直在使用泛型,我只是不知道它们叫什么。这是我的平均片段的示例。
public double arithmeticMean(List<Double> data) {
double sum = 0;
for (double number : data)
sum += number;
return sum / data.size();
}
我想知道是否有办法将其推广到其他数字变量(除了上面列出的形式之外。)
I was wondering if it is possible to override Java methods in a simpler way. My basic problem is that I have a collection of methods, an example can be calculating the mean of an array of values. My problem is that I want to have this method work for all number variables types (int long double float etc.) Is there any way to do this besides creating:
- A new method for each parameter type
- Having those new methods call one base method with parsed parameters
Any help is appreciated.
When reviewing the answer, I noticed that I have been using generics, I just didn't know what they were called. Here is an example of my mean snippet.
public double arithmeticMean(List<Double> data) {
double sum = 0;
for (double number : data)
sum += number;
return sum / data.size();
}
I was wondering if there was anyway to generalize this to other number variables (besides the forms listed above.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否研究过使用泛型并为
Double
、Float
、Integer
等定义新的计算器对象?Have you investigated using generics and define a new calculator object for
Double
,Float
,Integer
etc. ?正如布莱恩所说,仿制药将是实现这一目标的最佳方法。要实现 LinkedList 的平均值(不确定是否有办法用数组来实现此目的):
As Brian said, generics would be the best way to do this. To do the mean of a LinkedList (not sure if there's a way to do this with arrays or not):
你可以写这样的东西:
用法是:
You can write something like that:
The usage would be: