I need to create a TreeNode class, that will be able to store childs of two types: String and TreeNode. Number of childs is not fixed.
I want to create TreeNode objects somehow like this:
TreeNode a = new TreeNode("str", new TreeNode("str2"), "str3"); //Correct
TreeNode b = new TreeNode(a, "str4); //Correct
TreeNode c = new TreeNode(54); //Wrong
How can I do arguments type checking with wildcards or something else in compile time?
My inappropriate runtime solution:
private static final boolean debug = "true".equals(System.getProperty("debug"));
public <T> TreeNode (T... childs) {
if (debug) {
for (Object child : childs) {
if (!(child instanceof String || child instanceof TreeNode)) {
throw new RuntimeException("Type of childs must me Tree or String");
}
}
}
}
Parameters in constructor should have special meaning. Using varargs there is acceptable but it think that those are special cases. And you problem can be solved in another way.
So you could use this like this for example
where node3 and node4 are instaces of TreeNode;