Help me understand why two similar methods work differently.



  • I'm writing a library to process a single list, and there's a DDS class for testing:

    public class Node {
    public int value;
    public Node next;
    

    public Node (int value, Node next){
    this.value = value;
    this.next = next;
    }

    Now, to the methods, to begin with, we need to create two main ones, add an element to the beginning of the list and remove the first element at the beginning of the list, the code is:

    public static Node add (Node tail, int elem) {
    return (tail.next == null) ? tail.next = new Node(elem, null) : new Node(tail.value, add(tail.next, elem));
    }

    public static Node remove (Node tail) {
    return (tail.next == null) ? null : new Node(tail.value, remove(tail.next));
    }

    The trouble is, if you do that:

        public static void classTest () {
    Node testNode = NodeCreateAndPrint.nodeGenRecBackwards(9);// метод для создания экземпляра Node рандомом с передачей количества элементов
    add(testNode, 123);
    System.out.println("Test Node after_ add an element is " + NodeCreateAndPrint.nodePrintRecBackwards(testNode));
    add(testNode, 555);
    System.out.println("Test Node after_ add an element is " + NodeCreateAndPrint.nodePrintRecBackwards(testNode));
    remove(testNode);
    System.out.println("Test Node after_ rem an element is " + NodeCreateAndPrint.nodePrintRecBackwards(testNode));
    }

    This is the result:

    Testing SingleLUtils_2

    Test Node after_ add an element is 4-article2--grad5--grad3--grad9---article9---6--article9--grad7---grad123--Tentnull

    Test Node after_ adds an element is 4-state2-grad5-grad3--grad9---article9--6--grad1-X9--grad7---grad123--grad555--Statenull

    Test Node after_ rem an element is 4-article2--grad5--grad3--article9--article9--6--article9---state7--national123----555--Statenull
    Process finished with exit code 0

    i.e. the transferable copy does not change, if the element is removed, then, if added, it shall be modified (to him). Although if the output of the new Node method is to be derived, I will have the expected result.

    Why is this happening?



  • You have a method. remove returning a very different copy of the class. And you're the original. testNode

    It's two roots from different circuits with cross-references. Do it.

    testNode = remove(testNode);
    

    And it's gonna be okay.

    There is no such problem in the appendix as there is a change in the reference in the existing facility tail.next = ...and in the case of removal, the method shall return the new root of the chain.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2