简体   繁体   中英

How to reuse the code in situations where input param is a reference ?

This code would convert a linkedlist like : 1-> 2 -> 3 -> 4, into 1->3-2->4 (ie odd on left and even on right), except the problem caused by oddEvenSplitter function. This code will modify references by value. How to reuse the code in such situations where input is a reference ?

public void oddEvenSplitter (Node head, Node current, Node temp) {
    if (head == null) {
        head = temp;
        current = temp;
    } else {
        current.next = temp;
        current = temp;
    }
}

public void oddFirst( ) {
    if (first == null) {
        throw new NoSuchElementException();
    }

    Node temp = first;
    Node oddhead = null;
    Node odd = null;
    Node evenhead = null;
    Node even = null;

    while (temp != null) {

        if (temp.element % 2 == 0) {
            oddEvenSplitter(evenhead, even, temp);
        } else {
            oddEvenSplitter(oddhead, odd, temp);
        }
    }

    if (oddhead != null) {
        odd.next = evenhead;
        first = oddhead;
    }

}

Java does not have pass by reference. It always passes values. When you pass for example oddHead variable to oddEvenSplitter() method, what really happens is that a copy of oddHead variable is passed and from that point head and oddHead variables will be two separate variables, pointing on same object in the heap. So if you assign new value to head variable inside your method, the other one ( oddHead ) will remain unchanged. This is true for all other passed parameters as well.

As a solution you could create another object (like a DTO) and put all needed references inside it and pass it to your method. Then whenever you change those references, you will be able to get them in caller method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM