基于泛型类的改变方法

时间:2014-03-25 22:15:40

标签: java generics java.util.scanner

我正在尝试在java中创建一个简单的帮助器类,以从用户接收数字列表并将该List转换为用于数据操作的基本数组。我坚持在如何根据List对象的类类型更改扫描仪输入方法的第一步。最好的方法是什么?

    public static <N> List<N> promptList(String promptString, Class<N> resultType){
    prompt(promptString);
    List<N> inputList = new ArrayList<>();

    try (Scanner scanner = new Scanner(inStream)){
        do{
            inputList.add(scanner.nextDouble());    //switch scanner method based on type of N
        } while (true);
    } catch (Exception e){
        System.out.println("Input complete");
    }


    return inputList;   
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

使用if和原始包装类。 每个基本类都有一个公共静态变量TYPE,它是一个类。 例如:http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#TYPE

if (Double.TYPE = resultType)
 inputList.add(scanner.nextDouble();
else if (Integer.TYPE = resultType)
 inputList.add(scanner.nextDouble();
else if (FLOAT.TYPE = resultType)
 inputList.add(scanner.nextFloat();

以及更多ifs ....对于你所接受的所有原语作为可接受的输入。