如何交换 java 中 2 个对象的字段?

How to swap fields of 2 objects in java?

我有两个对象class TreeNode。这些称为 a 和 b,具有以下字段:

value
index
parent
leftChild 
rightChild

我想创建一个函数

swap(a,b)

将 a 的字段交换为 b 的字段,反之亦然。

我尝试创建这样的函数,但它相当冗长且效率低下,因为值没有按预期更改。 有什么简单的方法可以做到这一点吗?

我假设字段的类型是:

  • 值为字符串
  • 索引是整数
  • 父节点是树节点
  • leftChild 是 TreeNode
  • rightChild是TreeNode


所以使用经典的方法为每个字段交换值:

public static void swap(TreeNode a, TreeNode b) {
    String tempValue = a.value;
    a.value = b.value;
    b.value = tempValue;

    int tempIndex = a.index;
    a.index = b.index;
    b.index = tempIndex;

    TreeNode tempNode = a.parent;
    a.parent = b.parent;
    b.parent = tempNode; 

    tempNode = a.leftChild;
    a.leftChild = b.leftChild;
    b.leftChild = tempNode;    

    tempNode = a.rightChild;
    a.rightChild = b.rightChild;
    b.rightChild = tempNode;    
}

b的值复制到临时变量,将a的值设置为b,将临时变量的值复制到a。就这些了。

在 Java 中,你不能真正做到这一点(至少如果你的问题是字面上的意思)。

你的情况如何?类似于:

    // This is the aTreeNode instance.
    TreeNode a = new TreeNode("ValueA", 4711, parentA, leftChildA, rightChildA);

    // This is the aTreeNode instance.
    TreeNode b = new TreeNode("ValueB", 4712, parentB, leftChildB, rightChildB);

你有两个变量 ab,分别引用一个 TreeNode 实例(我称之为 aTreeNodebTreeNode,只是为了给它们我可以谈论的名字)。这些实例在各自的领域具有不同的价值。让我们描绘一下:

    a -> aTreeNode instance
         ------------------
         "ValueA"
         4711
         -> parentA instance
         -> leftChildA instance
         -> rightChildA instance

    b -> bTreeNode instance
         ------------------
         "ValueB"
         4712
         -> parentB instance
         -> leftChildB instance
         -> rightChildB instance

如果您调用类似 swap(a, b) 的方法,该方法将获取对 aTreeNodebTreeNode 实例的引用。由于该方法不知道这些引用来自何处(在我们的例子中,变量 ab,但它也可能是数组元素或其他方法调用的结果),它能做的最好的事情就是交换这些实例中的内容:

    a -> aTreeNode instance
         ------------------
         "ValueB"
         4712
         -> parentB instance
         -> leftChildB instance
         -> rightChildB instance

    b -> bTreeNode instance
         ------------------
         "ValueA"
         4711
         -> parentA instance
         -> leftChildA instance
         -> rightChildA instance

因此,在 swap(a, b) 调用之后,a 仍然引用 aTreeNode 实例,而 b 引用 bTreeNode,它们只是交换了它们的内容。实例内容的这种根本性变化不符合 Java 理念,会给你带来许多库 类 的麻烦,例如各种collections和地图。

因此,您最好在不调用方法的情况下交换两个变量:

    TreeNode a = new TreeNode("ValueA", 4711, parentA, leftChildA, rightChildA);
    TreeNode b = new TreeNode("ValueB", 4712, parentB, leftChildB, rightChildB);

    TreeNode temp = a;
    a = b;
    b = temp;

它更快、更干净,结果是:

    a -> bTreeNode instance
         ------------------
         "ValueB"
         4712
         -> parentB instance
         -> leftChildB instance
         -> rightChildB instance

    b -> aTreeNode instance
         ------------------
         "ValueA"
         4711
         -> parentA instance
         -> leftChildA instance
         -> rightChildA instance