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.