Java 具有可变参数类型和数量的方法
Java method with variable argument type and quantity
我在 Java 中对泛型和可变参数进行了一些研究,但我似乎无法找到如何将它们一起实现以创建具有灵活参数类型的方法(and/or 构造函数)和数量。例如,假设我想创建一个方法,可能需要一个整数数组或不固定数量的整数参数。我可以这样创建第一个:
public void example0 (int[] args) { }
以及后者本身:
public void example1 (int... args) { }
但是我怎样才能将它们组合成一个名字呢?而且,展望未来,我如何实现对多种数值类型(例如浮点数)的支持?一个例子将是一个很好的答案。
更新:
谢谢,但是对于一个更大的问题,我显然使用了一个过于简单的例子。考虑到任何数量的参数和任何类型,我将如何处理这个问题?所以说:
public void example(int[] args) {}
public void example(string arg0, int[] args) {}
public void example(string arg0, string arg1) {}
...
int...
参数可以接受整数和整数数组。您只需要一种方法来处理这两种情况。
public void example (int... args) { }
调用示例:
example(1, 2, 3);
example(new int[] { 1, 2, 3 });
And, looking to the future how could I implement support for multiple numeric value types, such as a float?
您可以尝试使用 Number
,它是 Integer
和 Float
的超类。但老实说,这既笨拙又低效,不值得。标准 API 方法往往只对所有数字类型进行重载。
public void example (int... args) { }
public void example (long... args) { }
public void example (float... args) { }
public void example (double... args) { }
在幕后,这两种方法都将使用相同的签名进行编译。例如vararg 是用于创建新数组的语法糖。
这两种方法都是等价的
public void example(int[] array)
public void example1 (int... args) { }
也可以接受int[]
。
所以这就够了。
要接受多种类型的数值,您可以使用泛型 class,该泛型是 Number
.
的子 class
例如:
public class Foo<T extends Number> {
// ...
}
你可以这样使用它:
Foo<Integer> fooInt = new Foo<>();
Foo<Float> fooFloat = new Foo<>();
但请注意,由于拆箱操作,它的效率会低于原始格式。因此,通常建议对每个原始类型使用重载方法:
public void example1 (int... args) { }
public void example1 (long... args) { }
public void example1 (double... args) { }
我在 Java 中对泛型和可变参数进行了一些研究,但我似乎无法找到如何将它们一起实现以创建具有灵活参数类型的方法(and/or 构造函数)和数量。例如,假设我想创建一个方法,可能需要一个整数数组或不固定数量的整数参数。我可以这样创建第一个:
public void example0 (int[] args) { }
以及后者本身:
public void example1 (int... args) { }
但是我怎样才能将它们组合成一个名字呢?而且,展望未来,我如何实现对多种数值类型(例如浮点数)的支持?一个例子将是一个很好的答案。
更新:
谢谢,但是对于一个更大的问题,我显然使用了一个过于简单的例子。考虑到任何数量的参数和任何类型,我将如何处理这个问题?所以说:
public void example(int[] args) {}
public void example(string arg0, int[] args) {}
public void example(string arg0, string arg1) {}
...
int...
参数可以接受整数和整数数组。您只需要一种方法来处理这两种情况。
public void example (int... args) { }
调用示例:
example(1, 2, 3);
example(new int[] { 1, 2, 3 });
And, looking to the future how could I implement support for multiple numeric value types, such as a float?
您可以尝试使用 Number
,它是 Integer
和 Float
的超类。但老实说,这既笨拙又低效,不值得。标准 API 方法往往只对所有数字类型进行重载。
public void example (int... args) { }
public void example (long... args) { }
public void example (float... args) { }
public void example (double... args) { }
在幕后,这两种方法都将使用相同的签名进行编译。例如vararg 是用于创建新数组的语法糖。
这两种方法都是等价的
public void example(int[] array)
public void example1 (int... args) { }
也可以接受int[]
。
所以这就够了。
要接受多种类型的数值,您可以使用泛型 class,该泛型是 Number
.
例如:
public class Foo<T extends Number> {
// ...
}
你可以这样使用它:
Foo<Integer> fooInt = new Foo<>();
Foo<Float> fooFloat = new Foo<>();
但请注意,由于拆箱操作,它的效率会低于原始格式。因此,通常建议对每个原始类型使用重载方法:
public void example1 (int... args) { }
public void example1 (long... args) { }
public void example1 (double... args) { }