Domanda

I am trying to make a generic binary search tree class that reads numbers from a file and builds a BST. I got all the separate numbers into an array, but I am stuck on how to convert them to an unspecified type.

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
    }

Is there a way to make this work? I tried just converting the string to a double, but then I had no way to get from double to n.

È stato utile?

Soluzione

All Number classes have a String constructor, so you can safely use reflection to invoke that constructor. Due to runtime type erasure, the type N is not accessible in your method, so you must pass a concrete class token to the constructor to get a reference to the constructor for the class of the type:

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));
        }
    }
}

Alternatively, you could pass the class object in with the method instead of the constructor, but that would somewhat defeat the "genericness" of your class.

I also removed spelling mistakes, abbreviated some code and added a while loop that seemed to be missing.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top