我遇到了一个场景,我需要一个公共和私有构造函数。需要一个私有构造函数来设置类型为私有内部类的私有字段。这是鼓励还是气馁?对于下面列出的场景,还有什么更好的解决方案?
请阅读评论,它更有意义地支持我的问题。谢谢,
public class CopyTree {
private TreeNode root;
public Copytree() { }
// private CopyTree(TreeNode root) { this.root = root; }
private static class TreeNode {
TreeNode left;
TreeNode right;
Integer element;
TreeNode(TreeNode left, TreeNode right, Integer element) {
this.left = left;
this.right = right;
this.element = element;
}
}
public CopyTree copyTree() {
CopyTree ct = new CopyTree();
ct.root = copyTree(root); // <---- QUESTION: Any cleaner solution ??
// cleaner solution appears to be a private constructor
// eg: CopyTree ct = new CopyTree(copyTree(root)); But can public and private constructor coexist together ?
return ct;
}
private TreeNode copyTree(TreeNode binaryTree) {
TreeNode copy = null;
if (binaryTree != null) {
copy = new TreeNode(null, null, binaryTree.element);
copy.left = copyTree(binaryTree.left);
copy.right = copyTree(binaryTree.right);
}
return copy;
}