简体   繁体   English

对同一方法使用不同的数据类型

[英]Using different data types for the same method

I want to use double values and int values separately in one method as parameters of the method how can I achieve that? 我想在一种方法中分别使用double值和int值作为方法的参数,如何实现呢? The method is multiplying two integer numbers and two double numbers in the same method. 该方法是在同一方法中将两个整数与两个双数相乘。 The output should be two lines one for the integer and the other for the double value 输出应为两行,一行为整数,另一行为double值

The most efficient way would be to overload the method : 最有效的方法是重载该方法:

void foo(int i)
void foo(double i)

But it is also valid to assign an int to a double , so you could also provide only : 但是将int赋给double也是有效的,因此您也可以只提供:

void foo(double i)

to accept both int and double . 接受intdouble

An alternative to overloading would be to define a generic class with a method that accepts the generic type : 重载的一种替代方法是使用可以接受通用类型的方法来定义通用类:

public class Bar<T extends Number>{
   public void foo(T t){
      ...
   }
}

And you could so instantiate them : 您可以实例化它们:

Bar<Integer> barInt = new Bar<>();
barInt .foo(3);
Bar<Double> barDouble = new Bar<>();
barDouble.foo(3);

Note that numeric wrappers consume more memory as primitive counter parts. 请注意,数字包装器将更多的内存用作原始计数器部分。
So the first way with overloading is really the most efficient. 因此,过载的第一种方法实际上是最有效的。

And you have still many other ways to handle this question. 而且您还有许多其他方法可以解决这个问题。 All that to say that you should use a way or another according your requirement. 这就是说您应该根据需要使用某种方式。

For some calculation which are typesafe for int/double you can just use this: 对于一些对于int / double类型安全的计算,您可以使用以下代码:

<T> T calc(T a, Tb) { };

If you want to use functions for a special Type (rounding/floating behaviour/...) you can use instance of and call a help method with INT or DOUBLE or ... or just do it in if-else . 如果要对特殊类型使用函数(四舍五入/浮动行为/ ...),可以使用的instance of并使用INTDOUBLE或...调用帮助方法,或者仅在if-else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM