如何限制在我的通用方法中仅接受一种类型?

unj*_*nj2 7 java generics types

我有一个通用函数foo,它接受任何类型并打印出来.

public static <T> T foo(T... arg) {
    List<T> foo = Arrays.asList(arg);
    for (T t : foo) {
      System.out.println(t);
    }
    return null;
  }
Run Code Online (Sandbox Code Playgroud)

如何确保收到的参数只有一种类型.例如,{1,'a',3}应该无效.它应该是所有数字或所有字符.我想接受所有整数或所有字符.

pol*_*nts 5

事实上你可以这样做:

static <T extends Comparable<T>> void f(T... args) {
    System.out.println(java.util.Arrays.toString(args));
}
public static void main(String[] args) {
    // all one type -- all of these compile!
    f(1, 2, 3); // prints "[1, 2, 3]"
    f('a', 'b', 'c'); // prints "[a, b, c]"
    f("a", "b", "c"); // prints "[a, b, c]"
    f(1D, 2D, 3D); // prints "[1.0, 2.0, 3.0]"

    // this is not preventable
    f(1, (int)'a', 3); // prints "[1, 97, 3]"

    // mixture of types -- none of these compile!
    //f(1, 'a', 3); // compilation error!
    //f(1, '2', "3"); // compilation error!
    //f("a", "b", 'c'); // compilation error!
    //f(1, 2, 3D); // compilation error!
}
Run Code Online (Sandbox Code Playgroud)

这利用了以下事实:

因此,要匹配这些类型(以及可能的其他类型),我们绑定T如下:

这确实包括一些东西,例如java.util.Date哪些implements Comparable<Date>,以及无数许多其他类型,但如果你也想要允许Integer和那么你可能做的最好Character.


不过,千万记住Integer,Character,String,都是Object,所以其实一帮这些混合在一起的IS一种类型的列表:Object.

值得庆幸的是,情况并非如此Object implements Comparable<Object>; 否则上述解决方案将无效.


Mar*_*tin 1

T部分意味着所有的都args将是相同的类型。

如果您想将泛型类型限制为某种类型或子类型(例如整数),您可以执行以下操作:-

public static <T extends Integer> T foo(T... arg) {
    List<T> foo = Arrays.asList(arg);
    for (T t : foo) {
      System.out.println(t);
    }
    return null;
  }
Run Code Online (Sandbox Code Playgroud)