使用java中的泛型函数获取数组输入

时间:2017-08-31 12:30:12

标签: java arrays generics initialization utility

我想要做的是,我有一个UTILITY包,我想用get方法创建一个GetArray类,它创建一个数组并返回该数组,同样我想制作这个方法 generic所以我可以创建我想要的任何类型的数组。

问题出在循环中的arr[i] = in.next();语句中。 即,我将如何根据我想要构建的数组的类型分配值

public class GetArray {

    /**
     * @param takes a scanner varable
     * @return returns an array of all the elements you specify
     */

    public static <T> int[] get(Scanner in) {

        System.out.print("enter array size :  ");
        int ar_size = in.nextInt();

        System.out.print("arr elements: ");
        T arr[] = new T[ar_size];

        for (int i = 0; i < ar_size; i++) {
            arr[i] = in.next();
        }
        return arr;
    }
}

我将从main.java调用此方法,因此我将扫描程序传递给它

2 个答案:

答案 0 :(得分:0)

如果您想拥有通用数组,那么您必须像这样修改代码

      public class GetArray {

/**
 * @param takes a scanner varable
 * @return returns an array of all the elements you specify
 */

@SuppressWarnings("unchecked")
public static <T> T[] get(Scanner in) {

    System.out.print("enter array size :  ");
    int ar_size = in.nextInt();

    System.out.print("arr elements: ");
    Object arr[] =  new Object[ar_size];

    for (int i = 0; i < ar_size; i++) {
        arr[i] =  (T)in.next();
    }
    return (T[]) arr;
}

}

答案 1 :(得分:0)

要拥有正确的数组类型,您需要传递元素的类:

public static <T> T[] get(Scanner in, Class<T> clazz) {

    System.out.print("enter array size :  ");
    int ar_size = in.nextInt();

    System.out.print("arr elements: ");
    T arr[] = (T[])Array.newInstance(clazz, ar_size);

    for (int i = 0; i < ar_size; i++) {
        arr[i] = clazz.cast(in.next());
    }
    return arr;
}

更新:但Scanner.next总是返回一个字符串,所以我担心你必须测试该类才能知道使用哪种Scanner方法:

    for (int i = 0; i < ar_size; i++) {
        Object elem = null;
        if (clazz == Byte.class) {
            elem = in.nextByte();
        } else if (clazz == Short.class) {
            elem = in.nextShort();
        } else if (clazz == Integer.class) {
            elem = in.nextInt();
        } else if (clazz == Long.class) {
            elem = in.nextLong();
        } else if (clazz == Float.class) {
            elem = in.nextFloat();
        } else if (clazz == Double.class) {
            elem = in.nextDouble();
        } else if (clazz == BigInteger.class) {
            elem = in.nextBigInteger();
        } else if (clazz == BigDecimal.class) {
            elem = in.nextBigDecimal();
        } else if (clazz == Boolean.class) {
            elem = in.nextBoolean();
        } else if (clazz == String.class) {
            elem = in.next();
        }
        arr[i] = clazz.cast(elem);
    }