我正在尝试制作一个通用的二进制搜索树类,该类从文件中读取数字并构建BST。我将所有单独的数字都放入一个数组中,但是我对如何将它们转换为未指定的类型感到困惑。

class ModifiedBinarySearchTree <N extends Number & Comprable<N>>{
    private BinaryNode<N> root;

    public void treeInput(String fileName) throws Exception{
    BufferedReader br = new BufferedReader( new FileReader(fileName));
    String[] nums = br.readLine().split("\\s");
    for(String num : nums){
         //do something to cast number as type n
         //I tried:
         N number = N.valueOf(num);
         insert(number);
         //but that gave me a compile error
    }

有没有办法使这项工作?我只是尝试将字符串转换为双精度型,但是后来我无法将双精度型转换为n。

最佳答案

所有 Number 类都有一个String构造函数,因此您可以安全地使用反射来调用该构造函数。由于存在runtime type erasure,因此无法在您的方法中访问N类型,因此必须将具体的类标记传递给构造函数,以获取对该类型的类的构造函数的引用:

class ModifiedBinarySearchTree <N extends Number & Comparable<N>>{
    private BinaryNode<N> root;
    private final Constructor<N> constructor;

    // pass in a Number class, eg new ModifiedBinarySearchTree(Integer.class)
    public ModifiedBinarySearchTree(Class<N> clazz) {
        try {
            constructor = clazz.getConstructor(String.class);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public void treeInput(String fileName) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            for (String num : line.split("\\s")) {
                insert(constructor.newInstance(num));
        }
    }
}

另外,您可以使用方法而不是构造函数来传递类对象,但这将在某种程度上破坏类的“泛型”。

我还消除了拼写错误,缩写了一些代码,并添加了一个似乎缺少的while循环。

10-06 05:45
查看更多