代码之家  ›  专栏  ›  技术社区  ›  Benjamin Brownlee

变量类型和数量的Java方法

  •  0
  • Benjamin Brownlee  · 技术社区  · 6 年前

    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) {}
    ...
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   davidxxx    6 年前

    public void example1 (int... args) { } 也可以接受 int[] . 所以这就足够了。
    要接受多种类型的数值,可以使用泛型类,泛型是 Number .

    例如:

    public class Foo<T extends Number> {
       // ...
    }
    

    你可以用它比如:

    Foo<Integer> fooInt = new Foo<>();
    Foo<Float> fooFloat = new Foo<>();
    

    但请注意,由于取消装箱操作的缘故,它的效率将低于primitive。因此,通常建议对每个基元类型使用重载方法:

    public void example1 (int... args) { }
    public void example1 (long... args) { }
    public void example1 (double... args) { }
    
        2
  •  7
  •   John Kugelman Michael Hodel    6 年前

    一个 int... 参数可以同时接受int和int数组。你只需要一个方法来处理这两个问题。

    public void example (int... args) { }
    

    调用示例:

    example(1, 2, 3);
    example(new int[] { 1, 2, 3 });
    

    而且,展望未来,我如何实现对多个数值类型(如浮点)的支持?

    你可以试着用 Number ,这是两者的超类 Integer Float . 但老实说,这是尴尬和低效的,不值得。标准API方法往往只对所有数值类型具有重载。

    public void example (int... args) { }
    public void example (long... args) { }
    public void example (float... args) { }
    public void example (double... args) { }
    
        3
  •  1
  •   killjoy    6 年前

    两种方法都是等价的。

    public void example(int[] array)