java 如何编写一个接受多种类型的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2914695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:26:20  来源:igfitidea点击:

How can you write a function that accepts multiple types?

javavariablesfunctiontypes

提问by matthy

I have a function that should work on int[] and on String[] now i have made the same function with a int parameter and an String parameter however if it has to go this way its a bit copy paste work and doesn't look very organized is there a way to solve this and put these 4 functions in 2?

我有一个应该在 int[] 和 String[] 上工作的函数,现在我用一个 int 参数和一个 String 参数创建了相同的函数,但是如果它必须这样,它有点复制粘贴工作并且看起来不非常有条理有没有办法解决这个问题并将这 4 个功能放在 2 中?

    static public void print(String s)
    {
        System.out.println(s);
    }

    static public void print(int s)
    {
        System.out.println(s);
    }

    static public void printArray(String[] s)
    {
        for (int i=0; i<s.length; i++)
            print(s[i]);
    }

    static public void printArray(int[] s)
    {
        for (int i=0; i<s.length; i++)
            print(s[i]);
    }

Thanks Matthy

谢谢马蒂

回答by danben

With autoboxing / autounboxing, you can do this:

使用自动装箱/自动拆箱,您可以这样做:

public static void print(Object s) {
  System.out.println(s.toString());
}

public static <T> void printArray(T[] arr) {
  for (T t : arr) {
    print(t);
  }
}

The one drawback is that the argument to printArraymust be an array of a reference type, but unlike the varargs solution this will work for any reference type.

一个缺点是 to 的参数printArray必须是引用类型的数组,但与 varargs 解决方案不同,这适用于任何引用类型。

Edit: regarding the varargs solution and @matthy's question about combining the two methods into one (ie generifying it), you could also do something like this:

编辑:关于 varargs 解决方案和@matthy 关于将两种方法合二为一的问题(即对其进行泛化),您也可以执行以下操作:

static public <T> void print(T... ts) {
    for (T t : ts) {
      System.out.print(t + " ");
    }
    System.out.println("");
}

However, you still cannot call it on an array of primitives:

但是,您仍然不能在原始数组上调用它:

int[] x = { 1, 2 };
print(x);

Because Java takes Tto be int[]and will execute the toStringmethod of the array rather than iterate through the contents. If you call it on an array of Integeror other reference type then it will work also.

因为Java需要Tint[]和将执行toString通过内容的阵列的方法,而不是迭代。如果您在数组Integer或其他引用类型上调用它,那么它也可以工作。

回答by Rick

static public void print(String...strings){
    for(String str : strings){
        System.out.println(str);
    }
}

static public void print(int...ints){
    for(int i : ints){
        System.out.println(i);
    }
}

回答by ZeissS

Well, the Basic class java.lang.Object matches String as well as int, byte, ... (Autoboxing converts them to Integer, Byte and so on). The method String.valueOf()lets you create a string of these. (toString() is available too)

好吧,基本类 java.lang.Object 匹配 String 以及 int、byte、...(自动装箱将它们转换为 Integer、Byte 等)。该方法String.valueOf()允许您创建这些字符串。(toString() 也可用)

回答by b_erb

Use Generics, if applicable to your code:

如果适用于您的代码,请使用泛型:

static <T> void printArray(T[] s)
{
    for (int i=0; i<s.length; i++)
        System.out.println(s[i]);
}

回答by aioobe

Combining the previous answers yield:

结合前面的答案产生:

public class Test {

    static <T> void print(T... ts) {
        for (T t : ts)
            System.out.println(t);
    }

    public static void main(String... args) {
        String[] strArr = { "one", "two" };
        Integer[] intArr = { 3, 4 };
        String str = "five";
        int i = 6;

        print(strArr);
        print(intArr);
        print(str);
        print(i);
    }
}

Output:

输出:

one
two
3
4
five
6

回答by Usman Gill

class MyClass {
    public static void main(String[ ] args) {
        String name ="David";
        int age = 42;
        double score =15.9;
        char group = 'Z';
        System.out.println(group  + "\n" + name + " \n" + age + " \n" + score);
    }
}