是否可以使用原始对象中的属性创建新对象而不更改它?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