是否可以使用原始對象中的屬性創建新對象而不更改它?Java - 創建對象時無需更改原始對象
例如:
public void exampleTests() {
Tree t = Trees.makeTree(new int[]{2, 3, 4, 4, 1});//creating tree
assertTrue(t.contains(4)); //check if 4 is a node
assertFalse(t.contains(6));//check if 6 is a node
assertEquals(4, t.size()); //return size-nodes number (only different digits)
Tree t2 = t.add(6).add(7).add(6); // obj 2 take obj 1 and add 6 and 7 to it
assertFalse(t.contains(6)); // the first object should have no 6
assertTrue(t2.contains(6)); // the second object should have 6
樹木類:
public class Trees {
public static Tree makeTree(int[] elements) {
Tree tree = new Nodes();
for (int i : elements) {
tree.add(i);
}
return tree;
}
}
樹接口
public interface Tree {
public Tree add(int i);
public boolean contains(int i);
public int size();
public String elementsAsString();
節點類:
public class Node {
int i;
Node left;
Node right;
public Node(int data) {
this.i = data;
left = null;
right = null;
}
}
節點類別:
public class Nodes implements Tree {
private Node root;
public Nodes() {
this.root = null;
}
@Override
public Nodes add(int i) {
root = insertNode(root, new Node(i));
return new Nodes();
}
private Node insertNode(Node currentParent, Node newNode) {
if (currentParent == null) {
return newNode;
} else if (newNode.i > currentParent.i) {
currentParent.right = insertNode(currentParent.right, newNode);
} else if (newNode.i < currentParent.i) {
currentParent.left = insertNode(currentParent.left, newNode);
}
return currentParent;
}
我們在Java中稱之爲什麼?
在您的例子,你需要創建一個'add'方法它返回一個新的對象(即,在內部它需要注意創建一個新的'Tree'實例,其值爲'this',通過'add'方法應該做什麼調整。這裏的關鍵字是「不可變數據結構」。 –
@ C-Otto謝謝,我想在add方法中返回新的樹,但它似乎將它們添加到不同的樹 – james