我遇到了一個場景,我需要一個公共和一個私人構造函數。需要使用私有構造函數來設置私有類型爲私有內部類的私有字段。 這是被封住還是氣餒?否則對於下面列出的方案,什麼是更好的解決方案?一個類可以有公共和私有構造函數嗎?
請閱讀評論,這更有意義地支持我的問題。謝謝,
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;
}
檢查:http://stackoverflow.com/a/11360712/1544069 – ritesh
你爲什麼不接受一個答案?他們都花時間回覆你的帖子,所以你至少可以做回報。來吧;) – Andy
當然,我的歉意。請留意並感謝整個社區的幫助,同時感謝您的關注。 – JavaDeveloper